Reputation: 447
I have a Control Items Group that is bound to an ObservableCollection. The ItemTemplate for each of the items works if it is set to a TextBlock as:
<DataTemplate x:Key="SampleTemplate">
<TextBlock Text="{Binding FirstName}"/>
</DataTemplate>
I created a User Control with a TextBlock within it. I want to pass the above "FirstName" to the User Control. I am trying to do this by defining a DependencyProperty in the User control code behind as:
public static DependencyProperty SomeValueProperty = DependencyProperty.Register(
"SomeValue",
typeof(Object),
typeof(SampleControl));
public string SomeValue
{
get
{
return (string)GetValue(SomeValueProperty);
}
set
{
(this.DataContext as UserControlViewModel).Name = value;
SetValue(SomeValueProperty, value);
}
and in the MainWindow's ItemTemplate, I changed it to:
<DataTemplate x:Key="SampleTemplate">
<local:SampleControl SomeValue="{Binding FirstName}"/>
</DataTemplate>
But this does not work. I am not sure why this Binding is failing when the same Binding works fine for a TextBlock within MainWindow. What am I doing wrong here?
Upvotes: 0
Views: 452
Reputation: 67065
There is a lot I can see wrong and it could be any of these things breaking this:
public static DependencyProperty SomeValueProperty = DependencyProperty.Register(
"SomeValue", typeof(String), typeof(SampleControl),
new FrameworkPropertyMetaData(new PropertyChangedCallback(OnSomeValueChanged)));
private static void OnSomeValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((d as SampleControl).DataContext as UserControlViewModel).Name = e.NewValue;
}
public string SomeValue
{
get
{
return (string)GetValue(SomeValueProperty);
}
set
{
SetValue(SomeValueProperty, value);
}
}
Notice I am using a String
, and not Object
. And, doing extra work on changing values in the PropertyChangedCallBack
. And, I am only doing the basics in the SomeValue
POCO as the real work is done in SetValue
. Also of note, I did not do any exception handling, which could be your error also...if set's .Name
call fails in your current code, then SetValue
never hits
Upvotes: 1