In my project, I wanted a UserControl that can display different formats of an image (bitmap, svg), selected from a ListBox. The SelectedItem of the ListBox is bound to the appropriate view model, which in turn changes the DataContext of the UserControl, and what I want to achieve is for it to change the displaying control (an Image for bitmaps, a SharpVectors.SvgViewBox for svg files) through data templates. It does so, but raises data binding errors, as if the templates were still intact whilst the UserControl's DataContext has already been changed.
I should like to a) avoid any data binding errors even if they cause no visible problems b) understand what is happening, so I prepared a MWE, which, to my surprise, displays the same behaviour, so I can present it here.
My minimal UserControl is as follows:
<UserControl x:Class="BindingDataTemplateMWE.VersatileControl"
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:system="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
<DataTemplate DataType="{x:Type system:String}">
<TextBlock Text="{Binding Content.Length, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContentControl}}" />
</DataTemplate>
<DataTemplate DataType="{x:Type system:DateTime}">
<TextBlock Text="{Binding Content.DayOfWeek, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContentControl}}" />
</DataTemplate>
</UserControl.Resources>
<Grid>
<ContentControl
Content="{Binding .}" />
</Grid>
</UserControl>
The MainWindow that references this UserControl has the following XAML:
<Window x:Class="BindingDataTemplateMWE.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:BindingDataTemplateMWE"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListBox
Grid.Column="0"
SelectedItem="{Binding Selected}"
ItemsSource="{Binding Items}" />
<local:VersatileControl
Grid.Column="1"
DataContext="{Binding Selected}" />
</Grid>
</Window>
with the following code-behind (to make the MWE indeed minimal, I made the window its own DataContext, but originally there is a dedicated view model):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
namespace BindingDataTemplateMWE
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private object selected;
public event PropertyChangedEventHandler PropertyChanged;
public List<object> Items { get; }
public object Selected {
get { return selected; }
set {
selected = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Selected)));
}
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
Items = new List<object>() { "a string", DateTime.Now, "another string" };
}
}
}
When I select a different item in the list, the desired effect takes place: the UserControl displays the length if a string is selected and the day of week when a DateTime. Still, I get the following binding error when selecting a DateTime after a string:
Length property not found on object of type DateTime.
and conversely, selecting a string after a DateTime yields
DayOfWeek property not found on object of type String.
It is clear that what I am doing is not meant to be done, but I do not know what the correct paradigm is and what happens in the background. Please advise me. Thank you.
I've seen this problem often when creating complex data templates (several levels of nesting) when views are loaded/unloaded. Honestly, some of such errors I am ignoring completely.
In your case something similar happens because you are manipulating DataContext directly. At the moment the new value is set, the previous value is still used in bindings, which monitor for source change and will try to update the target.
In your scenario you don't need this constant monitoring, so an easy fix is to use BindingMode.OneTime:
<DataTemplate DataType="{x:Type system:String}">
<TextBlock Text="{Binding Content.Length, RelativeSource={RelativeSource AncestorType=ContentControl}, Mode=OneTime}" />
</DataTemplate>
Related
Evidently using "Resources" to set an control's DataContext does not do what I think. I'm trying to stick close to MVVM. The following is an experiment in setting DataContext.
The MainWindow has a TabControl with two tabs, each displaying my pet's name, initally "Sam". Clicking the "ChangeName" button on Tab 1 changes the pet's name (to "Daisy") as expected. It does not change on Tab 2.
The content of Tab 2 is a Page, with its own DataContext, SecondTabViewModel. So I need to adjust the DataContext in the TextBlock in order to get at MyPet's name. This compiles ok, and Intellisense brings up the right things, so somehow within the control is being set. But the pet's name does not change.
Does the "StaticResource" generate instantiate a new copy of MainWindow or something? Can someone help me out? I'd love to know why this doesn't work, and what would work. This strategy for setting local DataContext is supposed to work according to the docs at https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-5.0 but I must be misreading.
To abbreviate I've omitted some of the code (the pet class. But everything seems to be ok there, in I'm able to change the name on the first tab The Pet class implements INotifyPropertyChanged, I'm using the right handler etc.)
MainWindow.xmal
<Window x:Class="WpfApp9.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:WpfApp9"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<TabControl>
<TabItem Header="First Tab" Height="50">
<StackPanel>
<TextBlock Text="{Binding MyPet.Name}"/>
<Button Content="Change Name"
Command="{Binding ChangePetNameCommand}"/>
</StackPanel>
</TabItem>
<TabItem Header="Second Tab" Height="50">
<Frame Source="SecondTab.xaml"/>
</TabItem>
</TabControl>
</Grid>
</Window>
MainWindowViewModel
public class MainWindowViewModel
{
public Pet MyPet { get; set; }
public ICommand ChangePetNameCommand { get; set; }
public MainWindowViewModel()
{
MyPet = new Pet();
ChangePetNameCommand =
new RelayCommand(ChangePetName, (Object o) => true);
}
public void ChangePetName(object o)
{
MyPet.Name = "Daisy";
}
}
SecondTab.xmal
<Page x:Class="WpfApp9.SecondTab"
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:WpfApp9"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="SecondTab">
<Page.DataContext>
<local:SecondTabViewModel/>
</Page.DataContext>
<Page.Resources>
<local:MainWindowViewModel x:Key="M"/>
</Page.Resources>
<Grid>
<StackPanel>
<TextBlock Text="{Binding Source={StaticResource M},
Path = MyPet.Name}"/>
</StackPanel>
</Grid>
</Page>
SecondTabviewModel
namespace WpfApp9
{
public class SecondTabViewModel
{
public SecondTabViewModel()
{
}
}
}
The lines
<Page.Resources>
<local:MainWindowViewModel x:Key="M"/>
</Page.Resources>
in SecondTab.xaml are creating a second MainWindowViewModel instance.
In other words, SecondTab does not operate on the original MainWindowViewModel.
You would somehow have to pass a reference to the original MainWindowViewModel instance to SecondTabViewModel.
Instead of using a Frame and a Page, SecondTab could perhaps be a UserControl that simply inherits the DataContext from its parent element, and you could pass a view model object like
<TabItem Header="Second Tab" Height="50">
<local:SecondTab DataContext="{Binding SecondTabVM}"/>
</TabItem>
where SecondTabVM is a property of MainWindowViewModel that holds a SecondTabViewModel instance.
Learning C#, specifically WPF, and the MVVM framework. I'm creating a basic project that presents a MainWindow with a contentcontrol binding. Straightforward.
I have 2 views, each with a textbox. I have 2 buttons on the MainWindow, each allow me to toggle between views. However, when I enter data in a textbox, switch views, and come back, the data is gone. How can I persist that data to be consumed later?
Relevant code:
MainWindow.xaml
<Window x:Class="TestDataRetention.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:TestDataRetention"
xmlns:views="clr-namespace:TestDataRetention.Views"
xmlns:viewmodels="clr-namespace:TestDataRetention.ViewModels"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<DataTemplate DataType="{x:Type viewmodels:View1ViewModel}">
<views:View1View DataContext="{Binding}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type viewmodels:View2ViewModel}">
<views:View2View DataContext="{Binding}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="60"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="1" HorizontalAlignment="Right">
<Button x:Name="View1Button" Margin="10" Width="80" Content="View1" Click="View1Button_Click"/>
<Button x:Name="View2Button" Margin="10" Width="80" Content="View2" Click="View2Button_Click"/>
</StackPanel>
<ContentControl x:Name="Content" Grid.Row="0" Content="{Binding}"/>
</Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;
using TestDataRetention.ViewModels;
namespace TestDataRetention
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void View1Button_Click(object sender, RoutedEventArgs e)
{
DataContext = new View1ViewModel();
}
private void View2Button_Click(object sender, RoutedEventArgs e)
{
DataContext = new View2ViewModel();
}
}
}
View1View.xaml
<UserControl x:Class="TestDataRetention.Views.View1View"
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:TestDataRetention.Views"
xmlns:vm="clr-namespace:TestDataRetention.ViewModels"
mc:Ignorable="d"
FontSize="24"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.DataContext>
<vm:View1ViewModel/>
</UserControl.DataContext>
<Grid Background="AliceBlue">
<StackPanel>
<Label HorizontalAlignment="Center" Content="Enter View1 Stuff"/>
<TextBox x:Name="View1TextBox" Width="400" Height="50" Text="{Binding View1Words}" />
</StackPanel>
</Grid>
</UserControl>
View1View.xaml.cs
using System.Windows.Controls;
using TestDataRetention.ViewModels;
namespace TestDataRetention.Views
{
public partial class View1View : UserControl
{
public View1View()
{
InitializeComponent();
this.DataContext = new View1ViewModel();
}
}
}
View2 is obviously the same as View1 but with corresponding variables.
While there might also be a way to just have wpf cache it for you, you can just as easily save it properly and then have the input available at will.
Look here for two methods on how to:
How to save user inputed value in TextBox? (WPF, XAML)
At quick glance, you create new ViewModel each time your button is clicked, this will always create new ViewModel for your DataContext not using the original one.
Also this snippet from your code will create new ViewModel for your Control's DataContext regardless of the one the parent control has:
<UserControl.DataContext>
<vm:View1ViewModel/>
</UserControl.DataContext>
And I am not sure how you use your DataTemplate here:
<DataTemplate DataType="{x:Type viewmodels:View1ViewModel}">
<views:View1View DataContext="{Binding}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type viewmodels:View2ViewModel}">
<views:View2View DataContext="{Binding}"/>
</DataTemplate>
But generally, as a guidance for you to model your MVVM project, always keep in mind that XAML code is translated to C# while compiling. So when writing something like <vm:View1ViewModel/> you actually do new View1ViewModel().
So for you to use the DataContext your control inherited from its parent, you just use <UserControl DataContext="{binding}" for your UserControl.
And for your button click, you have to keep a pointer for your previously created ViewModel and assign it to the DataContext when needed, I suggest you to create these ViewModels only when needed to minimize memory consumption in large applications, like:
private View1ViewModel m_View1VM = null;
private void View1Button_Click(object sender, RoutedEventArgs e)
{
if (m_View1VM is null)
m_View1VM = new View1ViewModel();
this.DataContext = m_View1VM;
}
I want to know how can i change user control from my Parent window that i placed usercontrol into it.
I have an user control that have a grid and data grid in that. now i want change data grid properties in my window ... and i want add another control to my grid .
some thing like this
<window>
<usercontrol>
<usercontrol.datagrid backcolor=#ff00000>
<usercontrol/>
<window/>
or can i add a textblock into usercontrol grid like this code :
<window>
<usercontrol.grid>
<textblock grid.row=1/>
<usercontrol.grid/>
<window/>
All element in user control are public so i can make change from c# code but i want do that with xaml design mode
in windows form i create a user control inherit from data grid view then i custom it. i use it in 10 windows and in 11th window i need change data grid view a bit i dont change usercontrol because it change all windows so i just change that usercontrol is in 11th window
please help !
I think you should create a DependencyProperty for your DataGrid's BackgroundColor (or whatever property you want to change) inside your UserControl's code behind:
public static DependencyProperty GridColorProperty = DependencyProperty.Register("GridColor", typeof (Brush),
typeof (UserControl1),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions
.AffectsRender));
public Brush GridColor
{
get { return (Brush)GetValue(GridColorProperty); }
set { SetValue(GridColorProperty, value);}
}
After that you should bind your DataGrid's Color property to it in UserControl's XAML:
<DataGrid Background="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=YourControlType}, Path=GridColor}"/>
And now you can use the control like that:
<YourControlType GridColor="Green"/>
As for controls addition it depends on what outlook exactly you're trying to achieve. The most straightforward way would be to derive your user control from grid. Or may be deriving from ContentControl would be enough for your purposes
Edit:
That's how you could put inside a new control. Deriving your control from Grid:
<Grid x:Class="WpfApplication3.UserControl1"
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:app="clr-namespace:WpfApplication3" mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<DataGrid Background="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=app:YourControlType}, Path=GridColor}"/>
</Grid>
And you would use it like that:
<YourControlType GridColor="Green">
<Button Grid.Row="1"/>
</YourControlType>
But actually it's a pretty weird thing to do and I would better derive it from a ContentControl:
<ContentControl x:Class="WpfApplication3.YourControlType"
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:app="clr-namespace:WpfApplication3" mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<ContentControl.Template>
<ControlTemplate TargetType="ContentControl">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<DataGrid Background="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=app:YourControlType}, Path=GridColor}"/>
<ContentPresenter Content="{TemplateBinding Content}" Grid.Row="1"/>
</Grid>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
That's how you use it:
<YourControlType GridColor="Green">
<Button/>
</YourControlType>
As yet another possibility you could create a dependency property for your control's content. Code behind:
public static readonly DependencyProperty InnerContentProperty =
DependencyProperty.Register("InnerContent", typeof (FrameworkElement), typeof (YourControlType),
new FrameworkPropertyMetadata(default(FrameworkElement),
FrameworkPropertyMetadataOptions.AffectsRender));
public FrameworkElement InnerContent
{
get { return (FrameworkElement) GetValue(InnerContentProperty); }
set { SetValue(InnerContentProperty, value); }
}
UserControl's XAML:
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<DataGrid Background="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=WpfApplication3:UserControl1}, Path=GridColor}"/>
<ContentControl Grid.Row="1" Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=app:YourControlType}, Path=InnerContent}"/>
</Grid>
Usage:
<YourControlType GridColor="Green">
<YourControlType.InnerContent>
<Button/>
</YourControlType.InnerContent>
</YourControlType>
But if you want just a quick and simple answer to your initial question as it states, there is no way you can directly address an inner control of your UserControl from XAML. = )
I have a general question about data templates in WPF. Let's say I have an abstract class called "Question," and various subclasses like "MathQuestion," "GeographyQuestion," etc. In some contexts, rendering the questions as a "Question" using the "Question" data template is good enough, but let's say that I have a list of random Question objects of varying subclasses that I want to display in-turn. I want to display them to the user using their specific data templates rather than their generic Question data template, but since I don't know that at design time, is there anyway to tell WPF, "hey, here's a list of Quesitons, but use reflection to figure out their specific types and use THAT data template?"
What I've thought of so far: I thought that in addition to having my question collection, I could create another collection of the specific types using reflection and somehow bind that to "blah," then I'd get the desired affect, but you can only bind to DependencyProperties in WPF, so I'm not sure what I'd bind to. I really don't like this idea, and my gut tells me there's a more elegant way to approach this problem.
I'm not looking for specific code here, just a general strategy to accomplish what I'm trying to do. Also, I'm using MVVM for the most part if that helps.
Thanks
I'm thinking something like this should work right out of the box:
<UserControl.Resources>
<DataTemplate DataType="{x:Type vm:GenericQuestionViewModel}">
<v:GenericQuestion/>
</DataTemplate>
<DataTemplate DataType="{x:Type tvm:GeographyQuestionViewModel}">
<tv:GeographyQuestion/>
</DataTemplate>
<DataTemplate DataType="{x:Type tvm:BiologyQuestionViewModel}">
<tv:BiologyQuestion/>
</DataTemplate>
</UserControl.Resources>
<ContentControl Content="{Binding QuestionViewModel}">
Edit:
Yes, this definitely should work. Here's a more complete example:
Main View Model
public class MainWindowViewModel : ViewModelBase
{
public ObservableCollection<QuestionViewModel> QuestionViewModels { get; set; }
public MainWindowViewModel()
{
QuestionViewModels = new ObservableCollection<QuestionViewModel>
{
new GenericQuestionViewModel(),
new GeographyQuestionViewModel(),
new BiologyQuestionViewModel()
};
}
}
Question View Models
public abstract class QuestionViewModel : ViewModelBase
{
}
public class GenericQuestionViewModel : QuestionViewModel
{
}
public class GeographyQuestionViewModel : QuestionViewModel
{
}
public class BiologyQuestionViewModel : QuestionViewModel
{
}
Question User Controls
<UserControl x:Class="WpfApplication1.GenericQuestion" ...>
<Grid>
<TextBlock Text="Generic Question" />
</Grid>
</UserControl>
<UserControl x:Class="WpfApplication1.GeographyQuestion" ...>
<Grid>
<TextBlock Text="Geography Question" />
</Grid>
</UserControl>
<UserControl x:Class="WpfApplication1.BiologyQuestion" ...>
<Grid>
<TextBlock Text="Biology Question" />
</Grid>
</UserControl>
Main Window
<Window x:Class="WpfApplication1.MainWindow" ...
Title="MainWindow"
Height="900"
Width="525">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type local:GenericQuestionViewModel}">
<local:GenericQuestion />
</DataTemplate>
<DataTemplate DataType="{x:Type local:GeographyQuestionViewModel}">
<local:GeographyQuestion />
</DataTemplate>
<DataTemplate DataType="{x:Type local:BiologyQuestionViewModel}">
<local:BiologyQuestion />
</DataTemplate>
</Window.Resources>
<ItemsControl ItemsSource="{Binding QuestionViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentControl Content="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
Update
Kyle Tolle pointed out a nice simplification for setting ItemsControl.ItemTemplate. Here is the resulting code:
<ItemsControl ItemsSource="{Binding QuestionViewModels}"
ItemTemplate="{Binding}" />
Generally, if you need to dynamically change the DataTemplate based on some non-static logic, you'd use a DataTemplateSelector. Another option it to use DataTriggers in your DataTemplate to modify the look appropriately.
I thought this would be pretty simple to do but seems I must be missing something blinding obvious.
The problem is that I am passing values to my UserControl (BoxPanel) but the values are not displayed. The blue box is displayed without text.
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<l:BoxPanel Number="1" Text="Hi" />
</Grid>
</Window>
BoxPanel.xaml
<UserControl x:Class="WpfApplication1.BoxPanel"
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"
Height="50" Width="90">
<Border Background="Blue">
<StackPanel>
<TextBlock FontSize="20" HorizontalAlignment="Center"
Text="{Binding Number}" />
<Label FontSize="10" HorizontalAlignment="Center" Foreground="White"
Content="{Binding Text}" />
</StackPanel>
</Border>
BoxPanel.xaml.xs
public partial class BoxPanel : UserControl
{
public static readonly DependencyProperty NumberProperty =
DependencyProperty.Register("Number", typeof(decimal), typeof(BoxPanel));
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(BoxPanel));
public BoxPanel()
{
InitializeComponent();
}
public decimal Number
{
get { return (decimal)GetValue(NumberProperty); }
set { SetValue(NumberProperty, value); }
}
public string Text
{
get { return (string)base.GetValue(TextProperty); }
set { base.SetValue(TextProperty, value); }
}
}
Binding paths, by default, are rooted at the DataContext. But you wish to bind to properties defined on the UserControl. So you have to redirect them somehow. I usually just do it by ElementName.
<UserControl x:Class="WpfApplication1.BoxPanel"
x:Name="BoxPanelRoot"
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"
Height="50" Width="90">
<Border Background="Blue">
<StackPanel>
<TextBlock Text="{Binding Number, ElementName=BoxPanelRoot}" />
<Label Content="{Binding Text, ElementName=BoxPanelRoot}" />
</StackPanel>
</Border>
It seems a little odd at first, and somewhat annoying to redirect bindings like this, but it is preferrable than other methods which utilize the DataContext within the UserControl. If you block the DataContext by, say, setting it to the root of the UserControl, you have effectively blocked the best method of passing data into the UserControl.
Rule of thumb, when binding in a UserControl, leave the DataContext alone unless you are explicitly binding against data passed to the UserControl.