简体   繁体   中英

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:

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!

<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". I know it's not working because the OnSelectedStringPropertyChanged isn't being invoked! 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:

  SelectedString = "Defalut";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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