简体   繁体   English

更改依赖项属性的值不会在DataTemplate中触发属性值更改事件

[英]Changing the value of a dependency property doesn't fire a property value changed event in a DataTemplate

I built a UserControl with a dependency property like this: 我用这样的依赖项属性构建了一个UserControl

public MyUserContol()
{                
    InitializeComponent();
    SelectedString = "Defalut";
}

public string SelectedString
{
    get { return (string)GetValue(SelectedStringProperty); }
    set { SetValue(SelectedStringProperty, value); }
} 

// Using a DependencyProperty as the backing store for SelectedString.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedStringProperty =
    DependencyProperty.Register("SelectedString", typeof(string), typeof(MyUserContol),
    new FrameworkPropertyMetadata(OnSelectedStringPropertyChanged));

private static void OnSelectedStringPropertyChanged(DependencyObject source,
                                                    DependencyPropertyChangedEventArgs e)
{
    (source as MyUserContol).SelectedSatringChanged();
}

When I use it, it's working fine 当我使用它时,它工作正常

<UserContol:MyUserControl SelectedClient="blabla" />

but in a DataTemplate it dosn't work! 但是在DataTemplate它不起作用!

<DataGrid1:DataGrid x:Name="dg"   ItemsSource="{Binding MyDataTable}">
    <DataGrid1:DataGrid.Columns>
        <DataGrid1:DataGridTemplateColumn SortMemberPath="[Client]" Header="Date" >
            <DataGrid1:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <UserContol:MyUserControl SelectedClient="blabla" >
                </DataTemplate>
            </DataGrid1:DataGridTemplateColumn.CellTemplate>
    </DataGrid1:DataGrid.Columns>
</DataGrid1:DataGrid>

Its not changing the value to "blabla". 它不会将值更改为“ blabla”。 I know it's not working because the OnSelectedStringPropertyChanged isn't being invoked! 我知道它不起作用,因为未调用OnSelectedStringPropertyChanged The property stays the default value given from the constructor. 该属性保留构造函数提供的默认值。

Why isn't it working? 为什么不起作用?

I found it !!! 我找到了 !!!

i needed to remove from the Ctor this code: 我需要从Ctor中删除以下代码:

  SelectedString = "Defalut";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM