WinUI 3中如何在ItemsControl的DataTemplate内绑定UserControl依赖属性?
WinUI 3中ItemsControl模板内绑定父级UserControl依赖属性的实现方法
我有一个包含ItemsControl的自定义UserControl,需要将ItemsControl的DataTemplate内部控件的属性,绑定到该UserControl自身的依赖属性(例如名为MyProp的依赖属性)。原本期望的XAML写法如下:
<UserControl> ... <ItemsControl> <ItemsControl.ItemTemplate> <DataTemplate x:DataType="MyType"> <custom:ControlThatExpectsMyType SomeProperty={x:Bind MyProp}> </custom:ControlThatExpectsMyType> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> ... </UserControl>
但MyProp是UserControl的属性而非MyType的属性,且WPF中的旧实现方式在WinUI 3中不生效,以下是WinUI 3的标准实现方案:
方案一:使用x:Bind绑定
WinUI 3的x:Bind默认基于当前数据上下文,要访问父级UserControl的属性,最直接的方式是给UserControl设置一个名称,通过名称直接引用:
- 给UserControl添加
x:Name标识:
<UserControl x:Name="RootUserControl"> ... <ItemsControl> <ItemsControl.ItemTemplate> <DataTemplate x:DataType="MyType"> <custom:ControlThatExpectsMyType SomeProperty="{x:Bind RootUserControl.MyProp, Mode=OneWay}"> </custom:ControlThatExpectsMyType> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> ... </UserControl>
注意:x:Bind默认是OneTime模式,如果需要依赖属性更新时同步刷新控件属性,要显式指定Mode=OneWay或TwoWay。
方案二:使用Binding绑定
如果习惯传统的Binding语法,可通过RelativeSource指定查找父级UserControl:
<UserControl> ... <ItemsControl> <ItemsControl.ItemTemplate> <DataTemplate x:DataType="MyType"> <custom:ControlThatExpectsMyType SomeProperty="{Binding MyProp, RelativeSource={RelativeSource AncestorType=UserControl}, Mode=OneWay}"> </custom:ControlThatExpectsMyType> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> ... </UserControl>
如果你的自定义UserControl有具体类型(例如MyCustomUserControl),可以将AncestorType改为自定义类型,提升查找精准度:
SomeProperty="{Binding MyProp, RelativeSource={RelativeSource AncestorType=local:MyCustomUserControl}, Mode=OneWay}"
需要提前在XAML头部引入自定义控件的命名空间,例如:xmlns:local="using:你的项目命名空间"。
内容的提问来源于stack exchange,提问作者Frustrated Soul
相关产品推荐
相关产品推荐

