5

DependencyPropertyUserControl に登録した非常に単純な例がありますが、これは期待どおりに機能していません。

OnPropertyChangedこのプロパティを、変更されるたびにイベントを発生させるように見える MainWindow の DP (Test と呼ばれる) にバインドしていますDependencyPropertyが、このバインドのターゲットである UserControl では、このプロパティが初めて通知されるようです。かわった。

これが私がコードでやろうとしていることです:

私のユーザーコントロール:

public partial class UserControl1 : UserControl
{
    public static readonly DependencyProperty ShowCategoriesProperty = 
        DependencyProperty.Register("ShowCategories", typeof(bool), typeof(UserControl1), new FrameworkPropertyMetadata(false, OnShowsCategoriesChanged));

    public UserControl1()
    {
        InitializeComponent();
    }

    public bool ShowCategories
    {
        get
        {
            return (bool)GetValue(ShowCategoriesProperty);
        }
        set
        {
            SetValue(ShowCategoriesProperty, value);
        }
    }

    private static void OnShowsCategoriesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        //this callback is only ever hit once when I expect 3 hits...

        ((UserControl1)d).ShowCategories = (bool)e.NewValue;
    }
}

MainWindow.xaml.cs

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();

        Test = true;  //this call changes default value of our DP and OnShowsCategoriesChanged is called correctly in my UserControl

        Test = false;  //these following calls do nothing!! (here is where my issue is)
        Test = true;
    }

    private bool test;
    public bool Test
    {
        get { return test; }
        set
        {
            test = value;
            OnPropertyChanged("Test");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string property)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(property));
        }
    }
}

MainWindow.xaml

<Window x:Class="Binding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:uc="clr-namespace:Binding"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"        
    Title="MainWindow" Height="350" Width="525">
  <Grid>
    <uc:UserControl1 ShowCategories="{Binding Test}" />
  </Grid>
</Window>
4

2 に答える 2

7

問題は、ShowCategories値をそれ自体に設定していることです。

((UserControl1)d).ShowCategories = (bool)e.NewValue;

ShowCategoriesの値はすでに変更されているため、この行は役に立ちません。それが、そもそもプロパティ変更コールバックにいる理由です。一見すると、これはノーオペレーションのように見えます。結局のところ、単にプロパティ値を現在の値に設定しているだけであり、WPF では何の変更も発生しません。

ただし、バインディングは双方向ではないため、プロパティ値を変更するとバインディングが上書きされます。そのため、コールバックが発生しなくなりました。コールバックで割り当てを削除するだけで完了です。

于 2012-10-08T16:59:04.520 に答える
1

バインディングモードをにしますTwoWay

于 2012-10-08T17:01:15.370 に答える