【问题标题】:wpf binding from a FindAncestor to Dependency Property of custom control从 FindAncestor 到自定义控件的依赖属性的 wpf 绑定
【发布时间】:2010-12-27 17:55:24
【问题描述】:

我有一个带有 DependencyProperty MyString 的自定义 WPF 控件

我在 View 上的 ItemsControl 中使用该控件,并希望从 ViewModel 中提取一个值。

当控件的 DataContext 成为 ItemsControl 的 ItemsSource 中的每个项目时,我以为我只能使用 FindAncestor 但它似乎不起作用......谁能看到我哪里出错了?

这是视图上的 XAML ...

<Grid>
    <ItemsControl ItemsSource="{Binding MyItems}" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" Name="myStack">
                    <ImportExceptions:ControlStrip MyString="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.MyStringOnViewModel}" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>

    </ItemsControl>
</Grid>

这是我设置依赖属性的自定义控件背后的代码...

public partial class ControlStrip
{

    public ControlStrip()
    {
        InitializeComponent();
    }

    public string MyString
    {
        get
        {
            return GetValue(MyStringProperty).ToString();
        }
        set
        {
            SetValue(MyStringProperty, value);
        }
    }

    public static readonly DependencyProperty MyStringProperty =
        DependencyProperty.RegisterAttached("MyString", typeof (string), typeof (ControlStrip));


}

【问题讨论】:

    标签: wpf binding controls


    【解决方案1】:

    控件的 DataContext 不会改变 - ImportExceptions:ControlStrip 的 DataContext 将是(除非明确指定)下一个可用的 DataContext,因为它“向上”可视化树...

    我从您的代码推断出您已将 View 的 DataContext 设置为具有“MyItems”和“MyStringOnViewModel”属性的 ViewModel - 您应该能够简单地将 MyString 属性直接绑定到 ViewModel,例如

    <ImportExceptions:ControlStrip MyString="{Binding Path=MyStringOnViewModel}" />
    

    【讨论】:

      【解决方案2】:

      您的代码看起来不错。可能您在 DataContext 引用中出错了。 ItemsControl 的DataContext 很可能已经是MyStringOnViewModel。因此,在 Path 属性中的 DataContext 之后省略 .MystringOnViewModel。如果不能,您能否提供更多代码,或者发布一个简化的代码,模仿 DataCon、文本的设置方式?

      【讨论】:

      • 正如您所怀疑的,我在 DataContext 参考中发现了错误。感谢您的帮助
      猜你喜欢
      • 1970-01-01
      • 2019-05-26
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多