且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF列表框按钮来选择项目

更新时间:2023-10-14 12:34:10

  VAR curItem =((ListBoxItem的)myListBox.ContainerFromElement((按钮)发送方))的内容;
 

I have a listbox with some textblocks and a button -- in the button's codebehind it calls a method passing the currently selected listbox item, this works great. The issue is that when I select an item and then click the button on another item it doesn't update the "SelectedItem" property -- is there a way Xaml or C# that I can force a button click to select the parent ListBoxItem?

Xaml

<DataTemplate>
    <Grid>
        <Button x:Name="myButton" Click="myButton_Click" Height="30" Width="30">
            <Image Source="Resources\Image.png" />
        </Button>
        <TextBlock Text="{Binding DataField}"></TextBlock>
    </Grid>
</DataTemplate>

var curItem = ((ListBoxItem)myListBox.ContainerFromElement((Button)sender)).Content;