如何解决ItemsControl和DataTemplate绑定到自身
我有一个ViewModel的窗口,其中的ObservableCollection<SomeObject>
名为Collection
。 SomeObject
包含两个字段,分别为:Property1
和Property2
。在该窗口中,我想添加UserControls。 UserControl有两个依赖项属性,也分别命名为:Property1
和Property2
。在窗口xaml
文件中,我这样创建了ItemsControl
:
<ItemsControl
ItemsSource="{Binding Collection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel>
</StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:SomeUserControl
Property1="{Binding Path=Property1}"
Property2="{Binding Path=Property2}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
是否可以在UserControl中仅具有一个依赖项属性SomeObject
并将其绑定在DataTemlete
中?像这样:
<DataTemplate>
<local:SomeUserControl
SomeObject="{Binding Path=this}"/>
</DataTemplate>
this
表示Collection
中的对象(在ItemsSource="{Binding Collection}
中定义)。因此,基本上,它只是绑定自身。
编辑:我现在有了这个主意:
在SomeObject
类中定义getter:
public SomeObject GetItself => this
,然后在DataTemplate
中使用:SomeObject="{Binding Path=GetItself}"
。它正在工作,但是我认为必须有一种更好的方法来实现此目标,而无需创建GetIteself
字段。
解决方法
我认为它可行
<DataTemplate>
<local:SomeUserControl
SomeObject="{Binding .}"/>
</DataTemplate>
或者只是
<DataTemplate>
<local:SomeUserControl
SomeObject="{Binding}"/>
</DataTemplate>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。