[英]How to use ElementName when binding to UIElement within template?
我试图弄清楚在绑定到与我要绑定的项目位于同一模板中的列表框时如何解决使用 ElementName 的问题。 当我运行下面显示的代码时,我收到以下错误:
System.NullReferenceException:“对象引用未设置为 object 的实例。”
命令参数为 null。
此外,没有迹象表明 Debug output window 中存在任何绑定错误。
我曾尝试使用DataTemplate 内的 Binding ElementName 中建议的 x:Reference 方法,但这引发了以下错误:
System.Windows.Markup.XamlParseException:'由于循环依赖,无法调用 MarkupExtension.ProvideValue。 MarkupExtension 内的属性不能引用引用 MarkupExtension 结果的对象
我的代码如下所示:
<ContentControl Grid.Row="0" Grid.RowSpan="2" HorizontalAlignment="Center" Width="Auto"
Height="Auto" VerticalAlignment="Top" Name="AddDeviceContentControl">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding ChooseNewDevice}" Value="true">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<ListBox Name="AddDeviceList" ItemsSource="{Binding Source={StaticResource DeviceTypes}}" >
<ie:Interaction.Triggers>
<ie:EventTrigger EventName="SelectionChanged">
<ie:InvokeCommandAction
Command="{Binding AddDeviceCommand}"
CommandParameter="{Binding ElementName=AddDeviceList, Path=SelectedItem}"/>
</ie:EventTrigger>
</ie:Interaction.Triggers>
</ListBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
注意:我在这里使用内容控件和模板,因为我希望列表不可见,除非 ChooseNewDevice 布尔值为真。 我选择不使用弹出窗口,因为我希望列表框 SelectedItem 在列表关闭时清除,但弹出窗口会保存 state。 如果有某种方法可以清除 XAML 中的列表框 SelectedItem(为了遵循 MVVM),这也可以解决我的问题。
正如其他人在这里所建议的那样,您应该通过在 ViewModel 上移动由SelectedItem
属性更改触发的逻辑来替换 XAML 中的交互触发器。
您的 XAML 会变得更简单,如下所示:
<ListBox ItemsSource="{Binding Source={StaticResource DeviceTypes}}"
SelectedItem="{Binding SelectedItem}">
<ListBox.Style>
<Style TargetType="ListBox">
<Setter Property="Visibility" Value="Visible"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ChooseNewDevice}" Value="true">
<Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.Style>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.