【问题标题】:WPF bind property to Dependency Property in child controlWPF 将属性绑定到子控件中的依赖属性
【发布时间】:2010-08-20 09:46:06
【问题描述】:

我创建了一个包含单个组合框的自定义 UserControl。组合框中当前选定的值绑定到自定义 UserControls 依赖属性。

XAML:

<UserControl>
    <ComboBox
        ItemsSource="{Binding AllEntries}"
        SelectedItem="{Binding SelectedEntry}" />
</UserControl>

后面的代码:

public partial class MyCombobox : UserControl
{
    public static DependencyProperty SelectedEntryProperty =
        DependencyProperty.Register("SelectedEntry",
            typeof(ComboboxEntry),
            typeof(MyCombobox));

    public ComboboxEntry SelectedEntry
    {
        get { return (ComboboxEntry)GetValue(SelectedEntryProperty); }
        set { SetValue(SelectedEntryProperty, value); }
    }
}

现在的问题是另一个组件包含这个扩展的组合框控件。在包含控件中,当用户在组合框中选择一个新值时,我想运行一些逻辑。我对如何设置那个钩子有点迷茫。 MyCombobox 必须公开一个从 SelectedEntry 依赖属性中的 PropertyChanged 回调触发的自定义事件吗?看起来很老套,但我想不出另一种方法。

【问题讨论】:

    标签: c# wpf xaml dependency-properties


    【解决方案1】:

    为什么不直接使用另一个绑定?

    <OuterControl>
        <StackPanel>
            <local:MyCombobox x:Name="myComboBox"/>
            <TextBlock Text="{Binding SelectedEntry, ElementName=myComboBox}"/>
        </StackPanel>
    </OuterControl>
    

    【讨论】:

    • 我正要回来删除问题(在我检查的第一个小时内它没有得到任何答案)......但你是对的,另一个绑定是我试图做的,但是我在后面的代码中使用 DataContext 属性做了很多丑陋的黑客攻击,所以我搞砸了所说的绑定。它现在可以正常工作,使用您描述的 bind-through-elementname 方法。我会接受并把它留在这里,给你一些代表,但我怀疑它会帮助其他在这里绊倒的人。干杯! :)
    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 2013-12-17
    • 2012-08-29
    • 2012-11-08
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多