WPF从FindAncestor到依赖项属性自定义控件的
我有一个自定义WPF控件绑定一个DependencyProperty MyString的WPF从FindAncestor到依赖项属性自定义控件的
我使用的是控制一个ItemsControl内对我的观想从出鱼的值ViewModel。
由于控件的DataContext成为ItemsControl的ItemsSource中的每个Item,我认为我只能使用FindAncestor,但dosnt似乎可以工作......任何人都可以看到我要出错的地方吗?
继承人的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));
}
您的代码看起来不错。可能你在DataContext参考中犯了一个错误。在所有可能性中,ItemsControl的DataContext已经是MyStringOnViewModel。因此,在Path属性中的DataContext之后省略.MystringOnViewModel。如果不是,你可以提供更多的代码,或者发布一个简单的代码来模拟DataCon,文本是如何设置的?
的DataContext的控件不会改变 - 对于ImportExceptions:ControlStrip
的DataContext将(除非明确指定)下一个DataContext可用,因为它向上“可视化树”...
我推断fr OM你的代码,你已经设置的DataContext查看到一个视图模型与性能“MyItems”和“MyStringOnViewModel” - 你应该能够简单地将MyString的属性直接绑定到视图模型,就像
<ImportExceptions:ControlStrip MyString="{Binding Path=MyStringOnViewModel}" />
我怕你打我;-) – Dabblernl 2009-12-17 18:01:09
我以为这是一个领带? ;) – kiwipom 2009-12-17 18:03:39
正如您怀疑我在DataContext参考中找到了错误。谢谢你的帮助 – 2009-12-21 16:12:44