【发布时间】: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));
}
【问题讨论】: