我有2个===
,数字和颜色。
数字 ComboBoxes
选项将更改颜色 ComboBox
的{{1}}。
如果新选择的项目与上一个项目具有相同的名称,例如“红色”,我想防止颜色 Item Source
触发ComboBox
事件。 ComboBox
和SelectionChanged
中的“红色”。
此Item Source 1
更改颜色 Item Source 2
的{{1}}。
ComboBox
不触发SelectionChanged事件
如果我将Item Source
用于ComboBox
,并且<ComboBox x:Name="cboNumbers"
SelectedItem="{Binding Numbers_SelectedItem}"
IsSynchronizedWithCurrentItem="True"
HorizontalAlignment="Left"
Margin="190,55,0,0"
VerticalAlignment="Top"
Width="120"
SelectionChanged="cboNumbers_SelectionChanged"/>
<System:String>1</System:String>
<System:String>2</System:String>
</ComboBox>
// Change Item Source with Selection
//
private void cboNumbers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (vm.Numbers_SelectedItem == "1")
{
vm.Colors_Items = colors1;
}
else if (vm.Numbers_SelectedItem == "2")
{
vm.Colors_Items = colors2;
}
}
与上一个项目具有相同的名称,它将不会触发List<string>
{{1} }事件。
Item Source
触发SelectionChanged事件
我想对SelectedItem
使用此自定义ComboBox
SelectionChanged
,因此我可以绑定多个值,但是会触发<ComboBox x:Name="cboColors"
ItemsSource="{Binding Colors_Items}"
SelectedItem="{Binding Colors_SelectedItem}"
IsSynchronizedWithCurrentItem="True"
HorizontalAlignment="Left"
Margin="190,55,0,0"
VerticalAlignment="Top"
Width="120"
SelectionChanged="cboColors_SelectionChanged"/>
// Colors Item Source 1
public List<string> colors1 = new List<string>()
{
"Red", //<-- same name (doesn't fire event)
"Green",
"Blue"
};
// Colors Item Source 2
public List<string> colors2 = new List<string>()
{
"Red", //<-- same name (doesn't fire event)
"Yellow",
"Purple"
};
class
事件。
List<ViewModel.MyColors>
Item Source
答案 0 :(得分:0)
这是我正在使用的hack。它仍然会触发SelectionChanged Event
,但是会忽略通常会在触发时运行的代码,因为我已将该代码移至绑定到SelectedItem
的ViewModel String
上。
组合框
public static string colors_PreviousItem;
private void cboColors_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Save the Previous Item
if (!string.IsNullOrEmpty(vm.Colors_SelectedItem))
{
colors_PreviousItem = vm.Colors_SelectedItem;
}
// Select Item
vm.Colors_SelectedItem = SelectItem(vm.Colors_Items.Select(c => c.Name).ToList(),
colors_PreviousItem
);
// I used to have the code I want to run in here
}
// Select Item Method
//
public static string SelectItem(List<string> itemsName,
string selectedItem
)
{
// Select Previous Item
if (itemsName?.Contains(selectedItem) == true)
{
return selectedItem;
}
// Default to First Item
else
{
return itemsName.FirstOrDefault();
}
}
ViewModel
// Selected Item
//
private string _Colors_SelectedItem { get; set; }
public string Colors_SelectedItem
{
get { return _Colors_SelectedItem; }
set
{
var previousItem = _Colors_SelectedItem;
_Colors_SelectedItem = value;
OnPropertyChanged("Colors_SelectedItem");
// Ignore if Previous Item is different than New Item
if (previousItem != value)
{
// Moved the code I want to run in here
// I want to ignore the code in here when the SelectionChanged Event fires
// and the Previous and Newly Selected Items are the same
}
}
}