wpf从FindAncestor绑定到自定义控件的依赖项属性

时间:2009-12-17 17:03:28

标签: wpf binding controls

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

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

由于控件的DataContext成为ItemsControl的ItemsSource中的每个Item,我以为我只能使用FindAncestor但它看起来很有用......有人能看到我出错的地方吗?< / p>

看看视图中的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));


}

2 个答案:

答案 0 :(得分:3)

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

我从你的代码中推断出你已​​经将View的DataContext设置为具有属性'MyItems'和'MyStringOnViewModel'的ViewModel - 你应该能够简单地将MyString属性直接绑定到ViewModel,比如

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

答案 1 :(得分:1)

您的代码看起来很好。可能你在DataContext引用中出错了。在所有可能的情况下,ItemsControl的DataContext已经是MyStringOnViewModel。因此,在Path属性中的DataContext之后省略.MystringOnViewModel。如果没有,你可以提供更多的代码,ore会发布一个模仿DataCon,文本是如何设置的简化吗?

相关问题