如何显示TextBox中ListBoxes多绑定中项的属性值

本文关键字:绑定 属性 ListBoxes 显示 TextBox 何显示 | 更新日期: 2023-09-27 18:28:03

我有一个TextBox,我想在代码隐藏(带有一些事件,例如MouseDown)中显示所选项目的属性值

属性的类型为Int16

我在这里看到了类似的问题,但是:

TextBox2.Text = ((Helmet) listhelmets.SelectedItems).protection;

这对我不起作用,我看到的其他建议也不起作用。

<ListBox x:Name="listweapons" Height="214" Width="248" ItemsSource="{Binding ListWeapon}" 
         IsSynchronizedWithCurrentItem="True" Canvas.Left="211" Canvas.Top="72" 
         PreviewMouseLeftButtonDown="weapons_PreviewMouseLeftButtonDown"
         PreviewMouseMove="weapons_PreviewMouseMove" 
         SelectedValuePath="attack">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Path=Image}" Width="56" Height="61"/>
                <TextBox Height="30" Width="30">
                    <Binding Path="_attack" />
                </TextBox>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

如何显示TextBox中ListBoxes多绑定中项的属性值

不能将ListBox.SelectedItemCollection类型的对象强制转换为Helmet类型,因此应该使用listhelmetsSelectedItem属性,而不是SelectedItems,如下所示:

TextBox2.Text = ((Helmet) listhelmets.SelectedItem).protection; 

如果protection不是string,也不要忘记在行的末尾使用ToString()