1

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

但是我不知道如何设置设置器来设置作为封闭控件一部分的属性(即外部世界)。我想我有这个倒退?

4

2 回答 2

1

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:

CustomItem item = (CustomItem)listBox1.SelectedItem;
MessageBox.Show(item.ShortName);

And your xaml is as follows:

<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>

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.

于 2009-05-13T08:04:39.107 回答
1

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

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

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

希望这会有所帮助..

祝你好运!

于 2009-05-13T08:19:17.553 回答