当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Getting name of control (listbox) by selected item (listboxitem) - MVVM

问题描述:

I have many listbox in my project. I moving selected item from one listbox to another.

In XAML file i biniding SelectedItem to my property.

<GroupBox Header="A" Grid.Column="0">

<ListBox Width="200" Name="lbWMSmaterials" ItemsSource="{Binding WMSmaterialItems}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" DisplayMemberPath="Name" />

</GroupBox>

<GroupBox Header="B" Grid.Column="1">

<ListBox Width="200" Name="lbCommonMaterials" ItemsSource="{Binding commonMaterialItems}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" DisplayMemberPath="Name"/>

</GroupBox>

<Button Command="{Binding MoveListBoxItem}" CommandParameter="common_material_down" Grid.Column="5" Style="{StaticResource buttonStyleDown}" Name="d_c_m" />

<Button Command="{Binding MoveListBoxItem}" CommandParameter="common_material_up" Grid.Column="6" Style="{StaticResource buttonStyleUpAll}" Name="u_c_m" />

I'm binding command in my buttons to perform some logic, also i pass command parameter to know with button i clicked. Each button moving selected item to another listbox.

public DemoItem SelectedItem { get; set; }

public DelegateCommand<string> MoveListBoxItem

{

get

{

return new DelegateCommand<string>(

new Action<string>(

(e) =>

{

switch (e)

{

case "common_material_down":

if (SelectedItemDown != null)

{

WMSarticleItems.Add(SelectedItemDown);

this.Remove(SelectedItemDown);

}

break;

//... other cases

default:

break;

}

}),

(e) => { return true; });

}

I need to know name of listbox currently related with me SelectedItem property.

How to do it without breaking MVVM pattern?

(Workaround is create many SelectedItem property for each lisbox, but i want to have only one)

网友答案:

You're not using MVVM. In MVVM, we don't move UI objects, instead we manipulate data objects. So, if you were using MVVM, then you wouldn't need to know the name of any UI element.

Instead of that, you'd simply bind a SelectedItem property in your view model to the SelectedItem property of your ListBox *and add this data object (or a copy of it) into the collection the is data bound to the relevant ListBox that you want to move the item to. In this case, your ICommand code would be something like this:

Collection1.Remove(Collection1.Where(c => c.Equals(SelectedItem)).Single());
Collection2.Add(SelectedItem);

And your XAML would be something like this:

<ListBox ItemsSource="{Binding Collection1}" SelectedItem="{Binding SelectedItem}".../>
...
<ListBox ItemsSource="{Binding Collection2}" SelectedItem="{Binding SelectedItem2}"../>
分享给朋友:
您可能感兴趣的文章:
随机阅读: