[英]Can a user control perform binding when part of a ListView in WinUI?
I'm trying to use a UserControl-derived control (UpdateBlockControl) inside the DataTemplate of a ListView, like this:我正在尝试在 ListView 的 DataTemplate 中使用 UserControl 派生控件 (UpdateBlockControl),如下所示:
<ListView x:Name="AppsListView">
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:AppBase">
<StackPanel Orientation="Horizontal">
<local:UpdateBlockControl ImageSource="{x:Bind ImageSource}" AppName="{x:Bind Name}"/>
<TextBlock Text="{x:Bind Name}" Foreground="Orange" Margin="8,0,0,0" />
<TextBlock Text="{x:Bind ImageSource}" Margin="8,0,0,0" Foreground="LimeGreen"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
UpdateBlockControl
is derived from UserControl
and I'm trying to bind its properties (ImageSource and AppName) to the model's (AppBase) properties. UpdateBlockControl
派生自UserControl
,我试图将其属性(ImageSource 和 AppName)绑定到模型的 (AppBase) 属性。
You can see me trying to set up these bindings in the first item in the StackPanel.您可以看到我试图在 StackPanel 的第一项中设置这些绑定。 Just to see if the binding works at all, I also bind a couple of TextBlocks to these properties.只是为了查看绑定是否有效,我还将几个 TextBlock 绑定到这些属性。
The XAML for UserBlockControl is essentially this: UserBlockControl 的 XAML 本质上是这样的:
<StackPanel Orientation="Vertical">
<TextBlock Text=":-)"/>
<TextBlock Text="{x:Bind AppName}"/>
<TextBlock Text="{x:Bind ImageSource}"/>
</StackPanel>
When I run the application I see the following:当我运行应用程序时,我看到以下内容:
So the UserControl properties aren't working correctly it would seem: I get the:-) for the first TextBlock but the second and third TextBlocks are empty.因此,UserControl 属性似乎无法正常工作:我得到第一个 TextBlock 的 :-),但第二个和第三个 TextBlock 为空。 Their equivalents in the ListView do work however (see image, above).然而,它们在 ListView 中的等效项确实有效(见上图)。
Should I be able to use a user control insisde a DataTemplate like this ?我应该能够像这样使用用户控件插入 DataTemplate吗? If so, why aren't the bindings working?如果是这样,为什么绑定不起作用?
x:Bind
is Mode=OneTime
by default. x:Bind
默认为Mode=OneTime
。 So, once a DependencyProperty
is initialized inside the UserControl
, it won't be updated anymore.因此,一旦DependencyProperty
在UserControl
中被初始化,它就不会再被更新。
You need to add Mode=OneWay
to x:Bind
in UpdateBlockControl
.您需要将Mode=OneWay
添加到UpdateBlockControl
中的x:Bind
。
<StackPanel Orientation="Vertical">
<TextBlock Text=":-)" />
<TextBlock Text="{x:Bind AppName, Mode=OneWay}" />
<TextBlock Text="{x:Bind ImageSource, Mode=OneWay}" />
</StackPanel>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.