多个ListBoxes及其SelectedItem的问题

The*_*ner 0 c# wpf listbox

我正在使用WPF(C#,Visual Studio 2010,MVVM Light)并且遇到三个Listbox控件的问题.

所以情况就是这样:我有三个Listbox.第一个是"示例"的ID列表.第二个也是"相关项目"的ID列表.它们是我的程序中的示例和相关项目,它们代表动词(如语言类型).

如果单击这两个ListBox中的任何一个,它将填充第三个ListBox.两者互不影响,只有第三种.第三个不影响其他两个.第三个一次只能容纳一个项目.

除了一种情况外,它运作良好.假设'examples'ListBox包含ID 100002和100003.我们还说'相关项'ListBox包含ID 100004和100005.我单击100002,因此第一个ListBox的选定项成为该项.第三个列表框显示100002的详细信息(应该如此).然后我点击100004上的第二个列表框.这成为第二个列表框的选定项目,第三个列表框显示100004.到目前为止.但现在我想说无论出于什么原因我想再回到100002.由于它仍然是第一个列表框中的选定项目,因此再次单击它无效.视图模型中的setter甚至没有被触发,因此我无法在那里做任何事情.事实上,我不确定在这种情况下我的选择是什么.我确实考虑过使用'examples'的setter来设置'相关项'的选定项为null,反之亦然,但我意识到这将导致无限循环.

我也尝试使用一个变量链接到前两个ListBoxes的选定项目,但这并没有解决问题.

我也尝试过以下方法:

private LanguageItemViewModel _selectedExampleOrRelatedItemTestVM = null;
    public LanguageItemViewModel SelectedExampleOrRelatedItemTestVM
    {
        get { return _selectedExampleOrRelatedItemTestVM; }
        set
        {
            if (_selectedExampleOrRelatedItemTestVM != value)
            {
                Mediator.EventMediator.Instance.PassLanguageItemAsExampleOrRelatedItem(value);
                _selectedExampleOrRelatedItemTestVM = null;
                RaisePropertyChanged("SelectedExampleOrRelatedItemTestVM");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

因此,在触发相关事件之后,变量本身只是设置为null.这也行不通.

也许有人在那里有一些建议,甚至一些我没有考虑过的途径?谢谢.

Ami*_*iri 5

我有两个选择:

1)将ListBox.SelectedItem绑定到ViewModel到OneWay绑定,以避免在将ViewModel的属性设置为null时提到的无限循环.但是因为它可能不是你想要的东西,也许你需要通过ViewModel来改变SelectedItem,第二种方法就派上用场了.

2)当用户单击ListBox并将SelectedItem作为参数发送时,调用ViewModel 的方法.就像是:

XAML

<Window>
    ...
    <ListBox x:Name="ListBoxFirst" MouseUp="ListBox_OnMouseUp"/>
    ...
</Window>
Run Code Online (Sandbox Code Playgroud)

并在View的CodeBehind文件中:

private void ListBox_OnMouseUp(object sender, MouseButtonEventArgs e)
{
    var viewModel = DataContext as YourViewModelType;

    if (viewModel != null && ListBoxFirst.SelectedItem != null)
    {
        viewModel.YourImplementedMethod(ListBoxFirst.SelectedItem);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,每次用户再次点击该项时,都会重复调用该方法.

另外,您还可以通过BlendSDK库直接从XAML文件中调用该方法:

编辑过XAML

<Window xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
    ...
    <ListBox x:Name="ListBoxFirst">

        <i:Interaction.Triggers>

            <i:EventTrigger EventName="MouseUp" SourceName="ListBoxFirst">
                <i:InvokeCommandAction Command="{Binding YourViewModelCommand}"
                 CommandParameter="{Binding ElementName=ListBoxFirst, Path=SelectedItem}"/>
            </i:EventTrigger>

        </i:Interaction.Triggers>

    </ListBox>
    ...
</Window>
Run Code Online (Sandbox Code Playgroud)

交互命名空间驻留在:

System.Windows.Interactivity

祝好运 :)