我有一个带有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));
}