WPF 基础知识:如何在 DataTrigger 中设置外部属性?
我正试图让我的头脑围绕着 WPF 模型。
我有一个项目列表框。列表框内的项目是字符串标识符。这工作正常。我想要的是拥有它,以便当前选定的标识符项目可以在我的封闭控件的代码隐藏中访问:
我
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Width="320">
<Label Content="{Binding Path=ShortName}" Style="{StaticResource ListHeader}"/>
<TextBlock TextWrapping="Wrap" Text="{Binding Path=Description}" Style="{StaticResource ListText}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
认为我应该添加类似的内容:
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}" Value="True">
<Setter Property="" TargetName="">
<Setter.Value>
</Setter.Value>
</Setter>
</DataTrigger>
但我不知道如何设置设置器来设置作为封闭控件(即外部世界)一部分的属性。 我想我有这个倒退吗?
I"m trying to get my head wrapped around the WPF model.
I have a list box of items. Inside the list box items are string identifiers. This works fine. What I want is to have it so that the identifier from the currently selected item is accessible in my code-behind for the enclosing control.
I have this:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Width="320">
<Label Content="{Binding Path=ShortName}" Style="{StaticResource ListHeader}"/>
<TextBlock TextWrapping="Wrap" Text="{Binding Path=Description}" Style="{StaticResource ListText}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
And I think I should add something like:
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}" Value="True">
<Setter Property="" TargetName="">
<Setter.Value>
</Setter.Value>
</Setter>
</DataTrigger>
But I'm lost as to how to set-up the setter to set a property that's part of the enclosing control (ie, the outside world). I think I have this backwards somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您尝试从列表框外部访问选定列表框项目上的属性,那么您可以在后面的代码中执行以下操作:
并且您的 xaml 如下所示:
您只需将选定项目从列表框转换为对象类型,然后访问对象的属性。
希望这就是您所追求的。
If you are trying to access a property on a selected list box item from outside of the listbox then you can do the following in your code behind:
And your xaml is as follows:
You just cast the selecteditem from the listbox to your object type, then access the property on the object.
Hope this is what you were after.
您是否尝试过使用 SelectedValuePath财产?
当您在 ItemsSource 属性上有一个客户列表,并且将 SelectedValuePath 设置为名称时,您的 SelectedValue 属性将返回客户的名称而不是客户...
在后面的代码中,SelectedValue 将是名称, SelectedItem 将返回您的 Customer 对象.. 在我的示例中..
希望这会有所帮助..
祝你好运!
Have you tried using the SelectedValuePath property?
When you have a list of say Customers on the ItemsSource property, and you set the SelectedValuePath to Name, your SelectedValue property will return the name of the Customer in stead of the customer...
In your code behind, the SelectedValue will be the Name, the SelectedItem will return your Customer object.. in my example..
Hope this helps somehow..
Good luck!