代码之家  ›  专栏  ›  技术社区  ›  Andy Clarke

从findancestor到自定义控件的依赖属性的WPF绑定

  •  0
  • Andy Clarke  · 技术社区  · 16 年前

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

    我正在视图中的itemsControl中使用该控件,并希望从ViewModel中获取一个值。

    当控件的数据上下文成为项控件的项源中的每个项时,我以为我可以使用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));
    
    
    }
    
    2 回复  |  直到 16 年前
        1
  •  1
  •   Dabblernl    16 年前

    你的代码看起来不错。可能在DataContext引用中出错。无论如何,itemsControl的DataContext已经是myStringOnViewModel。因此,在path属性的dataContext后面省略.myStringOnViewModel。如果不能的话,你能提供更多的代码,或者发布一个简化的代码来模仿数据通信,文本是如何设置的?

        2
  •  3
  •   kiwipom    16 年前

    控件的DataContext未更改-的DataContext ImportExceptions:ControlStrip 将是(除非明确指定)下一个可用的DataContext,因为它将“向上”显示树…

    我从您的代码推断,您已将视图的DataContext设置为具有属性“myitems”和“myStringOnViewModel”的ViewModel,您应该能够简单地将myString属性直接绑定到ViewModel,例如

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