【问题标题】:WPF Basics: How to set an outside property in a DataTrigger?WPF 基础知识:如何在 DataTrigger 中设置外部属性?
【发布时间】:2009-05-13 07:41:07
【问题描述】:

我试图让我的头脑围绕 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>

但我不知道如何设置 setter 来设置作为封闭控件(即外部世界)一部分的属性。我想我以某种方式倒退了?

【问题讨论】:

    标签: wpf visual-studio-2008 datatrigger


    【解决方案1】:

    如果您尝试从列表框外部访问选定列表框项目的属性,则可以在后面的代码中执行以下操作:

    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>
    

    您只需将选定项从列表框中转换为您的对象类型,然后访问该对象的属性。

    希望这就是你所追求的。

    【讨论】:

    • 抱歉,所选项目不是自定义类,它是上面 ListBox.ItemTemplate 中包含的 StackPanel
    • 嗨 EvilFred,我完全按照您的设置设置了 Xaml,但是您将对象集合绑定到我假定的列表框的 itemsource 属性。列表框的 selecteditem 属性使您可以访问选定的绑定对象,而不是 UI 元素。
    • 哦,我明白了。人们在 WPF 中不断谈论的 UI 与非 UI 元素的神奇分离。谢谢!
    【解决方案2】:

    您是否尝试过使用SelectedValuePath 属性?

    如果您在 ItemsSource 属性上有一个客户列表,并且您将 SelectedValuePath 设置为 Name,您的 SelectedValue 属性将返回客户的名称而不是客户的名称...

    在您后面的代码中,SelectedValue 将是名称,SelectedItem 将返回您的客户对象.. 在我的示例中..

    希望这能有所帮助..

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-09
      • 2011-06-15
      • 1970-01-01
      • 2011-09-07
      • 2015-12-07
      • 2013-02-24
      • 2014-10-14
      • 2014-05-02
      相关资源
      最近更新 更多