MVVM 列表框 DataTemplate SelectedItem

Sti*_*ter 2 c# wpf mvvm

我正在使用带有DataTemplate如下所示的列表框(xaml 简化和变量名称已更改)。

<ListBox ItemsSource="{Binding Path=ObservCollectionItems}"
         SelectedItem="{Binding Path=SelectedItemVar, Mode=TwoWay}">
         <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding SomeVar}" />
                    <Border>
                        <StackPanel>
                            <Button Content="String1"
                                    Command="{Binding DataContext.Command1}
                                    RelativeSource={RelativeSource FindAncestor, ListBox, 1}}" />
                            <Button Content="String2" 
                                    Command="{Binding DataContext.Command2}
                                    RelativeSource={RelativeSource FindAncestor, ListBox, 1}}" />
                        </StackPanel>
                    </Border>
                </StackPanel>
            </DataTemplate>
         <ListBox.ItemTemplate>
 </ListBox>
Run Code Online (Sandbox Code Playgroud)

当我单击其中一个按钮时,我需要 SelectedItemVar(依赖属性)进行更新。SelectedItemVar 然后用于相应按钮的命令。SelectedItemVar 在单击TextBlock或时会更新Border,但在单击任一按钮时不会更新。我在这里找到了解决此问题的非 MVVM 解决方案。我不想在文件隐藏中添加代码来解决这个问题,就像他们在链接中所做的那样。

是否有可以在 XAML 中完成的干净解决方案。除了非 MVVM 解决方案,我还没有发现任何人有这个问题。我会认为这是相当普遍的。

最后,我Command="{Binding DataContext.CommandName} RelativeSource={RelativeSource FindAncestor, ListBox, 1}为命令绑定找到了这个。我不完全明白它在做什么,但我知道当我直接绑定到CommandName.

Ank*_*esh 5

您正在使用 MVVM .... 非常简单的解决方案是将 SelectedItem 作为参数传递给 Both 按钮的命令,然后使用参数的值设置 SelectedItem .....

代码

public class YourViewmodel
{
     //Other Variables
     
     
     public YourViewModelCtor()
     {
        Command1= new RelayCommand(Command1Func);
     }
     
     Public SelectedVar
     {
             get {return value;}
             Set { selectedVar=value;
                       OnPropertyChanged("SelectedVar");
              }
     }

     //Other Properties


     void Command1Func(object obj)
     {
              SelectedVar= obj as <Your Desired Type>;

              //Do your thing with SelectedVar ... Do the same for Command2
     }
}
Run Code Online (Sandbox Code Playgroud)

Xaml 中所需的更改

<StackPanel>
    <Button Command="{Binding DataContext.Command1}" CommandParameter="{Binding}"
            Content="String1" />
    <Button Command="{Binding DataContext.Command2}" CommandParameter="{Binding}"
            Content="String2" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

这将为您提供单击按钮的当前 ListBox 项目。

这应该这样做...... :)