WPF基础:如何在DataTrigger中设置外部属性?
我正试着让我的头脑围绕着WPF模型 我有一个项目列表框。列表框内的项目是字符串标识符。这很好。我想要的是拥有它,以便在封闭控件的代码隐藏中可以访问当前所选项目的标识符 我有这个:WPF基础:如何在DataTrigger中设置外部属性?,wpf,visual-studio-2008,datatrigger,Wpf,Visual Studio 2008,Datatrigger,我正试着让我的头脑围绕着WPF模型 我有一个项目列表框。列表框内的项目是字符串标识符。这很好。我想要的是拥有它,以便在封闭控件的代码隐藏中可以访问当前所选项目的标识符 我有这个: <ListBox.ItemTemplate> <DataTemplate> <StackPanel Width="320"> <Label Content="{Binding Path=ShortName}" Style="{StaticResource Lis
<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>
但是我不知道如何设置setter来设置作为封闭控件(即外部世界)一部分的属性。我想我的方法是向后的?如果您试图从列表框外部访问所选列表框项目的属性,那么您可以在代码中执行以下操作:
CustomItem item = (CustomItem)listBox1.SelectedItem;
MessageBox.Show(item.ShortName);
您的xaml如下所示:
<ListBox Height="100" Name="listBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Name="stackPanel1">
<Label Content="{Binding Path=Shortname}"/>
<TextBlock Text="{Binding Path=Description}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
您只需将selecteditem从列表框强制转换为对象类型,然后访问对象的属性
希望这就是您想要的。您尝试过使用该属性吗
当您在ItemsSource属性上有一个客户列表,并且将SelectedValuePath设置为Name时,SelectedValue属性将返回客户的名称,而不是客户的名称
在您的代码隐藏中,SelectedValue将是名称,SelectedItem将返回您的Customer对象..在我的示例中
希望这能有所帮助
祝您好运!很抱歉,所选项目不是自定义类,它是ListBox中包含的StackPanel。ItemTemplate在上面,我将Xaml设置为与您的完全相同,但我认为您正在将一组对象绑定到ListBox的itemsource属性。ListBox的selecteditem属性允许您访问绑定的object没有选择UI元素。哦,我明白了。在WPF中人们一直在谈论的UI与非UI元素的神奇分离。谢谢!