C# WPF组合框忽略已禁用的选定项更新
在下面的代码中,我希望combobox返回到最初选择的\u项,但是它没有,窗口上的combobox总是显示我选择的任何新项,并且与模型不同步,我还尝试始终调用OnPropertyChangedSelected\u项;无论值是否不同,组合框仍会显示新选择的项目并失去同步。也许我做得不对,但是,正确的方法是什么C# WPF组合框忽略已禁用的选定项更新,c#,wpf,combobox,C#,Wpf,Combobox,在下面的代码中,我希望combobox返回到最初选择的\u项,但是它没有,窗口上的combobox总是显示我选择的任何新项,并且与模型不同步,我还尝试始终调用OnPropertyChangedSelected\u项;无论值是否不同,组合框仍会显示新选择的项目并失去同步。也许我做得不对,但是,正确的方法是什么 namespace WpfApplication8 { public class Context : INotifyPropertyChanged { #re
namespace WpfApplication8
{
public class Context : INotifyPropertyChanged
{
#region Privates
bool c_Disabled = false;
#endregion
#region Ctors
public Context()
{
Items = new List<MyItem>();
Items.Add(new MyItem("Item 1"));
Items.Add(new MyItem("Item 2"));
Items.Add(new MyItem("Item 3"));
Selected_Item = Items[0];
c_Disabled = true;
}
#endregion
#region Properties
public List<MyItem> Items
{
get;
private set;
}
private MyItem c_Selected_Item;
public MyItem Selected_Item
{
get { return c_Selected_Item; }
set
{
if (c_Selected_Item != value)
{
if (!c_Disabled)
{
c_Selected_Item = value;
OnPropertyChanged("Selected_Item");
}
}
}
}
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string f_Prop_Name)
{
PropertyChangedEventHandler l_Handler = PropertyChanged;
if(null != l_Handler)
{
l_Handler(this, new PropertyChangedEventArgs(f_Prop_Name));
}
}
#endregion
}
public class MyItem
{
public MyItem(string f_Name)
{
Name = f_Name;
}
public string Name {get;set;}
}
}
和以下窗口:
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox
HorizontalAlignment="Center"
VerticalAlignment="Top"
ItemsSource="{Binding Items}"
SelectedItem="{Binding Selected_Item}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>
删除c_Disabled=true;从上下文法 c_Disabled总是正确的。你的问题不清楚。很明显,你的if条件总是正确的。如果你清楚地陈述了你的需求,人们可能会建议你哪里出了问题。你的选定项设置程序无法阻止组合框的SelectedItem发生更改,即使它没有设置其支持字段。只要绑定没有被重新评估,就不会发生任何事情。视图完全忽略了这一点-当然,因为您关于绑定如何工作的假设是错误的。@克莱门斯,不,我假设它不工作,因为我说过[quote]我还试图始终调用OnPropertyChangedSelected\u项[/quote]。这意味着即使我在忽略集合时重新触发属性更新,它也会被UI忽略。