C# WPF Prism Page connect - c#

I try to connect a page to my main window using WPF app .net framework and Prism framework.
What am I missing here?
App.xaml:
<prism:PrismApplication x:Class="Aplicatie2._0.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
xmlns:local="clr-namespace:Aplicatie2._0">
<Application.Resources>
</Application.Resources>
</prism:PrismApplication>
App.xaml.cs:
using Prism.Modularity;
using Prism.Ioc;
using System.Windows;
using System.ComponentModel;
using Prism.Unity;
using Aplicatie2._0.View;
namespace Aplicatie2._0
{
public partial class App : PrismApplication
{
protected override Window CreateShell()
{
return Container.Resolve<MainPage>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<MainPage>("MainPage");
containerRegistry.RegisterForNavigation<FirstQ>("FirstQ");
}
}
}
ViewModel->MainPageViewModel:
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Commands;
using System.Windows.Input;
using System.Windows;
using Prism.Regions;
using Aplicatie2._0.View;
namespace Aplicatie2._0.ViewModel
{
class MainPageViewModel : BindableBase
{
private string _Title = "Test";
private IRegionManager _regionManager;
public string Title
{
get
{
return _Title;
}
set
{
SetProperty(ref _Title, value);
}
}
public DelegateCommand PressButton { get; private set; }
public MainPageViewModel(IRegionManager regionManager)
{
PressButton = new DelegateCommand(Execute);
_regionManager = regionManager;
}
public void Execute()
{
MessageBox.Show("TEST");
_regionManager.RequestNavigate("MainContent", "FirstQ");
}
}
}
View->MainPage:
<Window x:Class="Aplicatie2._0.View.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:VM="clr-namespace:Aplicatie2._0.ViewModel"
xmlns:prism="http://prismlibrary.com/"
xmlns:local="clr-namespace:Aplicatie2._0.View"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d"
Title="{Binding Title}" Height="450" Width="800">
<Window.DataContext>
<VM:MainPageViewModel/>
</Window.DataContext>
<Grid>
<ContentControl prism:RegionManager.RegionName="MainContent"/>
<Button Content="Button" CommandParameter="FirstQ" HorizontalAlignment="Left" Margin="151,54,0,0" VerticalAlignment="Top" Width="75" Command="{Binding PressButton}"/>
</Grid>
</Window>
View->FirstQ
<Page x:Class="Aplicatie2._0.View.FirstQ"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Aplicatie2._0.View"
Background="White"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="FirstQ">
<Grid>
<TextBlock HorizontalAlignment="Left" Margin="249,108,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
</Grid>
</Page>
My window does not start. If I make MainPageViewModel constructor like this:
public MainPageViewModel()
window is open.
If I don't have:
<Window.DataContext>
<VM:MainPageViewModel/>
</Window.DataContext>
my bind's not work, whether I have or not
prism:ViewModelLocator.AutoWireViewModel="True"...
What did I miss?

You either have to
align the namespaces with the default convention (MyApp.Views for the views, MyApp.ViewModels for the view models)
register view and view model together
create your own convention to link the views' and view models' types
so that the ViewModelLocator can do his work.
From the code you posted, Aplicatie2._0.View.MainPage should be Aplicatie2._0.Views.MainPage and Aplicatie2._0.ViewModel.MainPageViewModel should be Aplicatie2._0.ViewModels.MainPageViewModel.

Related

C#: How to populate combo items in UserControl

The following code works by having the combobox populated by the C# code behind at run-time.
I would like to populate the user control combos declaratively from XAML, similar to how the description label is populated.
This code is just for my personal use, so I won't be using complex MVVM models. I'd ideally like a solution that passes string arrays from the main XAMLcode, to the user control as I'd like to know how to do that.
Thanks in advance :-)
//Main Window.xaml
<Window
x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="Car Details"
SizeToContent="WidthAndHeight">
<StackPanel>
<local:myControl
x:Name="myMake"
myDescription="Make" />
<local:myControl
x:Name="myModel"
myDescription="Model" />
<local:myControl
x:Name="myYear"
myDescription="Year" />
</StackPanel>
</Window>
//MainWindow.xaml.cs
using System.Windows;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//myMake is the name of a specific myControl
//myOption is the name of the combo within myControl
myMake.myOptions.ItemsSource = new string[] { "Ford", "Toyota" };
}
}
}
//myControl.xaml
<UserControl
x:Class="WpfApp1.myControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d">
<StackPanel>
<Label
Content="{Binding myDescription,FallbackValue=description}"
/>
<ComboBox
x:Name="myOptions"
Width="120" />
</StackPanel>
</UserControl>
//myControl.xaml.cs
using System.Windows;
using System.Windows.Controls;
namespace WpfApp1
{
public partial class myControl : UserControl
{
public myControl()
{
InitializeComponent();
this.DataContext = this;
}
public string myDescription
{
get { return (string)GetValue(myDescriptionProperty); }
set { SetValue(myDescriptionProperty, value); }
}
public static readonly DependencyProperty myDescriptionProperty = DependencyProperty.Register("myDescription", typeof(string), typeof(myControl), new PropertyMetadata(null));
}
}
You can declare an array of string in xaml like this:
<x:Array xmlns:s="clr-namespace:System;assembly=mscorlib" x:Key="myStringArray" Type="{x:Type s:String}">
<s:String>Ford</s:String>
<s:String>Toyota</s:String>
</x:Array>
Source: this answer
So your view becomes:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="Car Details" SizeToContent="WidthAndHeight">
<Window.Resources>
<!--Declaration of an array of string which is added to the ressources of the window-->
<x:Array xmlns:s="clr-namespace:System;assembly=mscorlib" x:Key="myStringArray" Type="{x:Type s:String}">
<s:String>Ford</s:String>
<s:String>Toyota</s:String>
</x:Array>
</Window.Resources>
<StackPanel>
<!--We get the array from the ressource by calling "StaticResource" with the key of the element to obtain-->
<local:myControl
x:Name="myMake" myDescription="Make" ArrayItemsSource="{StaticResource myStringArray}" />
<!--Do the same for the other usercontrol -->
<local:myControl
x:Name="myModel"
myDescription="Model" />
<local:myControl
x:Name="myYear"
myDescription="Year" />
</StackPanel>
In your usercontrol, you should not use this.DataContext = this; as this is bad practice since it prevents your usercontrol from inheriting the datacontext of the view (I know you are not planning on using MVVM but I think this should still be mentioned for other readers).
So because the datacontext is not the control, the bindings in the xaml of the usercontrol have to be modified like this: {Binding ElementName=myControlName, Path=theNameOfThePropertyIwantToBind}
I created a new dependency property to pass the array of string from the view so the usercontrol becomes:
Xaml:
<UserControl x:Class="WpfApp1.myControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1" x:Name="myControlName"
mc:Ignorable="d">
<StackPanel>
<Label
Content="{Binding ElementName=myControlName, Path=myDescription,FallbackValue=description}"
/>
<ComboBox
x:Name="myOptions" ItemsSource="{Binding ElementName=myControlName, Path=ArrayItemsSource}"
Width="120" />
</StackPanel>
The code behind:
public partial class myControl : UserControl
{
public myControl()
{
InitializeComponent();
//Bad practice
//this.DataContext = this;
}
public string myDescription
{
get { return (string)GetValue(myDescriptionProperty); }
set { SetValue(myDescriptionProperty, value); }
}
public string[] ArrayItemsSource
{
get { return (string[])GetValue(ArrayItemsSourceProperty); }
set { SetValue(ArrayItemsSourceProperty, value); }
}
public static readonly DependencyProperty myDescriptionProperty = DependencyProperty.Register("myDescription", typeof(string), typeof(myControl), new PropertyMetadata(null));
public static readonly DependencyProperty ArrayItemsSourceProperty = DependencyProperty.Register(nameof(ArrayItemsSource), typeof(string[]), typeof(myControl), new PropertyMetadata(null));
}

How to set the public variable value from the wpf user control?

I have one dll which contains the wpf user control.
I have one wpf window in another wpf project which contains the above user control in that.
I have two public properties in wpf user control.
I want to set those properties from the wpf window in which wpf user control is added.
I have tried to do it using dependency property as follows :
TestUserControl.xaml :-
<UserControl x:Class="TestDependencyProperty.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Label Content="test property" x:Name="lblTestProperty"/>
</Grid>
</UserControl>
TestUserControl.xaml.cs :-
using System.ComponentModel;
using System.Windows;
namespace TestDependencyProperty
{
/// <summary>
/// Interaction logic for TestUserControl.xaml
/// </summary>
public partial class TestUserControl
{
public TestUserControl()
{
InitializeComponent();
SetLabelText();
}
private void SetLabelText()
{
lblTestProperty.Content = TestProperty;
}
public static readonly DependencyProperty TestDependencyProperty =
DependencyProperty.Register("TestProperty",
typeof(string),
typeof(TestUserControl));
[Bindable(true)]
public string TestProperty
{
get
{
return (string)this.GetValue(TestDependencyProperty);
}
set
{
this.SetValue(TestDependencyProperty, value);
}
}
}
MainWindow.xaml :-
<Window x:Class="TestDependencyProperty.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:TestDependencyProperty"
>
<Grid>
<local:TestUserControl x:Name="ucTest" TestProperty="HelloWorld"/>
</Grid>
</Window>
I am expecting a label with content "HelloWorld".
So can anybody tell me how to do it ?
Thanks.
User Control XAML:
<UserControl x:Class="TestDependencyProperty.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication3"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Label Content="{Binding TestProperty}" x:Name="lblTestProperty"/>
</Grid>
</UserControl>
User Control Code:
public partial class TestUserControl : UserControl
{
public TestUserControl()
{
InitializeComponent();
}
public static readonly DependencyProperty TestDependencyProperty =
DependencyProperty.Register("TestProperty",
typeof(string),
typeof(TestUserControl));
[Bindable(true)]
public string TestProperty
{
get
{
return (string)this.GetValue(TestDependencyProperty);
}
set
{
this.SetValue(TestDependencyProperty, value);
}
}
}
You do not need SetLabelText();
Window Hosting User Control
<local:TestUserControl TestProperty="Test Text" x:Name="MyNewUserControl" />
in code behind if needed:
MyNewUserControl.TestProperty="New Value";
Dependency Properties have change notification built in to them so once a property is bound to them it will automatically get updated when the property does.

C# WPF OxyPlot error plot does not exist in namespace

Hi I have a problem configuring oxyplot in WPF. I have found a few solutions but nothing works. I have found out that this is the best http://blog.bartdemeyer.be/2013/03/creating-graphs-in-wpf-using-oxyplot/
but something still wrong and I get this error in XAML file:
the name plot does not exist in the namespace codeplex
MainWindow.xaml FILE:
<Window x:Class="OxyPlotDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:OxyPlotDemo"
xmlns:oxy="http://oxyplot.codeplex.com"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<oxy:Plot x:Name="Plot1" Title="A Graph" Model="{Binding PlotModel}" Margin="10" Grid.Row="1">
</oxy:Plot>
</Grid>
MainWindow.xaml.cs
using System.Windows;
namespace OxyPlotDemo
{
public partial class MainWindow : Window
{
private ViewModels.MainWindowModel viewModel;
public MainWindow()
{
viewModel = new ViewModels.MainWindowModel();
DataContext = viewModel;
InitializeComponent();
}
}
}
MainWindowModel.cs
using System.ComponentModel;
using OxyPlot;
namespace OxyPlotDemo.ViewModels
{
public class MainWindowModel : INotifyPropertyChanged
{
private PlotModel plotModel;
public PlotModel PlotModel
{
get { return plotModel; }
set { plotModel = value; OnPropertyChanged("PlotModel"); }
}
public MainWindowModel()
{
PlotModel = new PlotModel();
}
public event PropertyChangedEventHandler PropertyChanged;
//[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Maybe someone has better solution. I just need to display a few charts, that contains a lot of data from sensors, not in real time.
I've had a same issue with OxyPlot lib from NuGet, when migrating from lib version 1.x to 2.1.
SO i found, that in version 2.1 Plot class is moved to another library, see releases history at their github page.
That worked for me:
xmlns:oxy="http://oxyplot.org/wpf"
xmlns:oxycontrols="http://oxyplot.org/wpf/contrib"
<oxycontrols:Plot .../>
<Window x:Class="Universal_trc_csvParser.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Universal_trc_csvParser"
xmlns:oxy="http://oxyplot.org/wpf"
mc:Ignorable="d"
Title="Window1" Height="450" Width="800">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<oxy:PlotView Model="{Binding MyModel}"/>
</Grid>
</Window>
public class MainViewModel
{
public MainViewModel()
{
this.MyModel = new PlotModel { Title = "Example 1" };
this.MyModel.Series.Add(new FunctionSeries(Math.Cos, 0, 10, 0.1, "cos(x)"));
}
public PlotModel MyModel { get; private set; }
}
This worked for me.
I had the same issue.
So what i did was downgrade my "OxyPlot.Wpf" to version 1.0.0. and the example you speak of works fine, without the error "the name plot does not exist in the namespace".
<oxy:Plot x:Name="Plot1" Title="A Graph" Model="{Binding PlotModel}" Margin="10" Grid.Row="1">
</oxy:Plot>

Mvvm Light, UWP and code behind

Base on this excellent presentation from Laurent Bugnion at Xamarin Evolve 2014, I'm trying to create my first UWP/MVVM Light application.
I created a very simple Article : ObservableObject class with 2 string properties : Référence and Désignation.
In the view model associated to the article list view, I have an action to create a new article :
public ArticlesViewModel(IArticleService dataService, INavigationService navigationService)
{
ArticleService = dataService;
NavigationService = navigationService;
CréeArticleCommand = new RelayCommand(CréeArticle);
}
public RelayCommand CréeArticleCommand { get; private set; }
private void CréeArticle()
{
if (!CréeArticleCommand.CanExecute(null))
return;
NavigationService.NavigateTo(ViewModelLocator.ArticleDetail_Key,
new ArticleViewModel(new Article(),
ArticleService,
NavigationService));
}
here is the XAML for my Article detail view :
<!-- language: xaml -->
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UniversalTest1.UWP.Articles"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Editors="using:DevExpress.UI.Xaml.Editors"
x:Class="UniversalTest1.UWP.Articles.Article_Detail"
mc:Ignorable="d"
xmlns:vm="clr-namespace:UniversalTest1.Data.ViewModels.Articles;assembly=UniversalTest1.Data"
d:DataContext="{d:DesignInstance Type=vm:ArticleViewModel, IsDesignTimeCreatable=True}">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="Référence :" HorizontalAlignment="Left" Margin="24,15,0,0" VerticalAlignment="Top"/>
<TextBlock Text="Désignation :" HorizontalAlignment="Left" Margin="10,52,0,0" VerticalAlignment="Top"/>
<Editors:TextEdit Text="{Binding Article.Référence, Mode=TwoWay}" HorizontalAlignment="Left" Margin="100,8,0,0" VerticalAlignment="Top" Width="300"/>
<Editors:TextEdit Text="{Binding Article.Désignation, Mode=TwoWay}" HorizontalAlignment="Left" Margin="100,45,0,0" VerticalAlignment="Top" Width="500"/>
<Button Content="Sauver" Command="{Binding SauverCommand}" HorizontalAlignment="Left" Margin="102,84,0,0" VerticalAlignment="Top"/>
</Grid>
</Page>
My problem here is that I have to define the DataContext in the code behind of my page :
public sealed partial class Article_Detail : Page
{
public Article_Detail()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
DataContext = (ArticleViewModel)e.Parameter;
}
}
Is there a way to keep the design time DataContext as defined in the d:DataContext part of the Xaml's Page, and at runtime, get the DataContext from the Navigation parameter ?
My goal here is to have the less amount possible of code in the code behind. So I would like to define the runtime DataContext in the XAML also.
You can make use of dependency injection to create design or runtime service instances for your viewmodel. Using a view model locator you can do something like this:
public class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
if (!SimpleIoc.Default.IsRegistered<IArticleService>())
{
SimpleIoc.Default.Register<IArticleService, DesignArticleService>();
}
}
else
{
if (!SimpleIoc.Default.IsRegistered<IArticleService>())
{
SimpleIoc.Default.Register<IArticleService, ArticleService>();
}
}
SimpleIoc.Default.Register<ArticleViewModel>();
}
public ArticleViewModel ArticleViewModel => ServiceLocator.Current.GetInstance<ArticleViewModel>();
}
And in your App.xaml you register the locator
<Application
x:Class="UniversalTest1.App" // your namespace
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModel="using:UniversalTest1.Data.ViewModels"> // your namespace
<Application.Resources>
<ResourceDictionary>
<viewModel:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
</ResourceDictionary>
</Application.Resources>
</Application>
And then you can reference it in your xaml like this:
<Page
...
DataContext="{Binding ArticleViewModel, Source={StaticResource Locator}}">
You could also take a look at the sample code here https://mvvmlight.codeplex.com/SourceControl/latest#Samples/Flowers/Flowers.Data/ViewModel/ViewModelLocator.cs
For this, you need to use your own implementation of NavigationService. The concept is to navigate to your page and call your ViewModel at the same time to handle parameters and set the DataContext.
Here are two samples of this pattern:
Prism: https://github.com/PrismLibrary/Prism/blob/master/Source/Windows10/Prism.Windows/Navigation/FrameNavigationService.cs
Template10: https://github.com/Windows-XAML/Template10/blob/master/Template10%20(Library)/Services/NavigationService/NavigationService.cs

Define method WPF user control

I have this User control:
I added this user control to my Winforms application (simple BusyIndicator)
UserControl x:Class="Stackoverflow.MyBusyIndicator"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:xctk="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<xctk:BusyIndicator x:Name="busyIndicator" IsBusy="{Binding IsBusy}" />
</Grid>
</UserControl>
And all i want is define Method that i can access from c# code in order to stop this indicator.
I believe what you want to do this in the code behind?
public partial class MyBusyIndicator : UserControl
{
public void ToggleIndicator(bool isBusy)
{
// Just an example, in reality you will want to access the BusyIndicator object.
this.IsBusy = isBusy;
}
}
Your XAML code is fine, now just create a Dependency Property and call it "IsBusy", which you then can bind to in your UserControl XAML using a DataBinding (to visually indicate the IsBusy property state),
public partial class BusyIndicator : UserControl
{
public BusyIndicator()
{
InitializeComponent();
}
public bool IsBusy
{
get { return (bool)GetValue(IsBusyProperty); }
set { SetValue(IsBusyProperty, value); }
}
public static readonly DependencyProperty IsBusyProperty =
DependencyProperty.Register("IsBusy", typeof(bool), typeof(BusyIndicator),
new PropertyMetadata(false));
}
Try this :
<UserControl x:Class="Stackoverflow.MyBusyIndicator"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:xctk="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<xctk:BusyIndicator x:Name="myBusyIndicator" IsBusy="True" />
</Grid>
</UserControl>
Code Bahind :
namespace Stackoverflow
{
using System;
using System.Windows;
using System.Windows.Controls;
public partial class MyBusyIndicator : UserControl
{
public MyBusyIndicator()
{
this.InitializeComponent();
}
public void ShowIndicator(bool isBusy)
{
this.myBusyIndicator.IsBusy = isBusy;
}
}
}
If you have to access it through code-behind first provide a name attribute to the BusyIndicator control through Xaml first:
<xctk:BusyIndicator IsBusy="True" x:Name="busyIndicator" />
In your code behind create a method as below:
void SetIndicator(bool isBusy)
{
this.busyIndicator.IsBusy = isBusy;
}
If you are using MVVM bind your control's IsBusyProperty IsBusy={Binding IsBusy}
<xctk:BusyIndicator IsBusy={Binding IsBusy} />
And in your viewmodel define IsBusy property and create method as below:
void SetIndicator(bool isBusy)
{
IsBusy = isBusy;
}
So next time you want to set is as True call SetIndicator(true) or if you want to set it as false call SetIndicator(false).

Categories