Reputation: 23
The example given here is a simplification of the actual UserControl that I am trying to implement but it illustrates the structure and suffers from the same problem. The user control has a DependencyProperty Words that sets the text of textblock that is defined in the user control XAML.
public partial class MyControl : UserControl
{
public static readonly DependencyProperty WordsProperty = DependencyProperty.Register("Words", typeof(string), typeof(MyControl));
public MyControl()
{
InitializeComponent();
}
public string Words
{
get { return (string)GetValue(WordsProperty); }
set
{
m_TextBlock.Text = value;
SetValue(WordsProperty, value);
}
An INotifyPropertyChanged ViewModelBase class derived ViewModel is assigned to the mainWindow DataContext. The ModelText property set calls OnPropertyChanged.
class MainWindow : ViewModelBase
{
private string m_ModelString;
public string ModelText
{
get { return m_ModelString; }
set
{
m_ModelString = value;
base.OnPropertyChanged("ModelText");
}
}
}
In the MainWindow XAML binding is made to the UserControl and a TextBlock
<Window x:Class="Binding.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="218" Width="266" xmlns:my="clr-namespace:Binding.View">
<Grid>
<my:MyControl Words="{Binding ModelText}" HorizontalAlignment="Left" Margin="39,29,0,0" x:Name="myControl1" VerticalAlignment="Top" Height="69" Width="179" Background="#FF96FF96" />
<TextBlock Height="21" HorizontalAlignment="Left" Margin="59,116,0,0" Name="textBlock1" Text="{Binding ModelText}" VerticalAlignment="Top" Width="104" Background="Yellow" />
</Grid>
</Window>
The binding works for the textblock but not for the user control. Why can't UserControl DependencyProperty be bound in the same way as Control Properties?
Upvotes: 2
Views: 994
Reputation: 4770
I think that you should to assign the text to your UserControl's textbox by a binding and not by m_TextBlock.Text = value;
.
Maybe you could user a binding like this in your UserControl Xaml:
Text="{Binding Words
, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
Upvotes: 0
Reputation: 16648
The culprit is:
m_TextBlock.Text = value;
WPF does not directly use properties backed by a DP.
If you want to update m_TextBlock.Text
when the WordsProperty
is modified, either bind that textblock to Words
, or use the PropertyChangedCallback
in UIPropertyMetadata
:
public static readonly DependencyProperty WordsProperty =
DependencyProperty.Register("Words",
typeof(string),
typeof(MyControl),
new UIPRopertyMetadata(
new PropertyChangedCallback(
(dpo, dpce) =>
{
//Probably going to need to first cast dpo to MyControl
//And then assign its m_TextBlock property's text.
m_TextBlock.Text = dpce.NewValue as string;
})));
Consider dpo
the sender, and dpce
the event args.
Upvotes: 0