簡體   English   中英

如何在具有綁定的列表框中獲取所選項目?

[英]How to get a selected item in a list box with bindings?

我在 c# 中有一個 wpf 應用程序,我的問題是現在我有一個帶有綁定的列表框,我的問題是如何從列表框中的文本框中獲取文本?

我的列表框 XAML:

            <ListBox x:Name="chats_lb_friends" ItemsSource="{Binding Friends_pic}" Height="870" Width="280" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF535664" FontSize="18" FontFamily="/Nextopia Launcher v.2.0;component/fonts/#Mont DEMO" FontWeight="Bold" IsSynchronizedWithCurrentItem="False" MinWidth="280" SelectionChanged="chats_lb_friends_SelectionChanged_1">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel x:Name="chats_lb_friends_stackpanel" Orientation="Horizontal">
                            <Ellipse x:Name="chats_lb_friends_img" Width="25" Height="25" Stroke="{Binding status}" StrokeThickness="2">
                                <Ellipse.Fill>
                                    <ImageBrush Stretch="Fill" ImageSource="{Binding imagePath}"/>
                                </Ellipse.Fill>
                            </Ellipse>
                            <TextBlock x:Name="chats_lb_friends_txt" Text="{Binding username}" Margin="5,0,0,0" />
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

我想要什么:

ListBoxItem MyItem = chats_lb_friends.SelectedItem as ListBoxItem;
if(MyItem != null)
{
    StackPanel sp = MyItem.Content as StackPanel;
    if(sp != null && sp.Children.Count > 0)
    {
        TextBlock textBlock = sp.Children[0] as TextBlock;
        if(textBlock != null)
        {
            string text = textBlock.Text;
        }
    }
}

但這不起作用有沒有人知道為什么?

提前感謝,對不起我的英語

假設您有一個帶有公共字符串屬性用戶名的 PersonViewModel。

您的 lisbox 的 itemssource 似乎沒有被綁定。 但是讓我們假設您可以擁有一個具有 2 個公共屬性的 window 視圖模型:

public ObservableCollection<PersonViewModel> People {get;set;} = new ObservableCollection<PersonViewModel>()

public PersonViewModel SelectedPerson {get;set;}

所以你可以將 listBox 的 SelectedItem 綁定到 SelectedPerson

<ListBox SelectedItem="{Binding SelectedPerson" ItemsSource="{Binding People}"

然后你可以這樣做:

var name = SelectedPerson.username;

您可能還需要一些 null 檢查

var name = SelectedPerson?.username ?? "";

您應該在所有視圖模型上實現 inotifypropertychanged,並且您還可能希望從視圖模型屬性的設置器中引發 notifypropertychanged。

更多關於在此處使用 mvvm 處理選定項目的信息:

https://social.technet.microsoft.com/wiki/contents/articles/30564.wpf-uneventful-mvvm.aspx#Select_From_List_IndexChanged

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM