【问题标题】:WPF Event Not Raised when Dependency Property Changed依赖属性更改时未引发 WPF 事件
【发布时间】:2016-10-06 10:58:21
【问题描述】:

我有以下基于this链接的“重选项”的自定义控件:

public partial class SelectableContentControl : ContentControl
{
    public SelectableContentControl()
    {
        InitializeComponent();
        var isCheckedDesc = DependencyPropertyDescriptor.FromProperty(IsCheckedProperty, typeof(SelectableContentControl));
        isCheckedDesc.AddValueChanged(this, IsCheckedPropertyChanged);
    }

    public bool IsChecked
    {
        get { return (bool)GetValue(IsCheckedProperty); }
        set { SetValue(IsCheckedProperty, value); }
    }

    public static readonly DependencyProperty IsCheckedProperty =
        DependencyProperty.Register("IsChecked", typeof(bool),
          typeof(SelectableContentControl), new PropertyMetadata(false));

    private void IsCheckedPropertyChanged(object sender, EventArgs e)
    {
        var selectable = Content as IAmSelectable;
        if (selectable != null) selectable.IsSelected = IsChecked;
    }
}

SelectableContentControl定义的样式如下:

<Style TargetType="{x:Type controls1:SelectableContentControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls1:SelectableContentControl}">
                <CheckBox IsChecked="{TemplateBinding IsChecked}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

...和我的用法:

<controls:SelectableContentControl Grid.Row="2" Content="{Binding Dummy}" IsChecked="{Binding Dummy.IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

我希望在 UI 上的 IsChecked 值更改时调用 IsCheckedPropertyChanged,但这不会发生。有人看到我错过了什么吗?

【问题讨论】:

    标签: c# wpf xaml controls dependency-properties


    【解决方案1】:

    TemplateBindingOneWay 模式下工作,这意味着该值仅在源到目标的方向上更新(您的控件是源,模板内的CheckBox 是目标)。如果您希望绑定在TwoWay 模式下工作,您应该使用普通的Binding

    <ControlTemplate TargetType="{x:Type controls1:SelectableContentControl}">
        <CheckBox IsChecked="{Binding IsChecked, RelativeSource={RelativeSource TemplatedParent}}" />
    </ControlTemplate>
    

    注意,绑定时不需要指定Mode=TwoWay,因为CheckBox.IsChecked属性默认是双向绑定的。

    请参阅this question 了解更多详细信息。

    【讨论】:

    • 谢谢,就是这样。在我想通之前,宇宙会因热死而终结。
    猜你喜欢
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 2018-05-20
    • 2011-02-13
    • 1970-01-01
    相关资源
    最近更新 更多