gpt4 book ai didi

wpf - 当它不属于 ItemsSource 时,自动从 ComboBox 中清除 SelectedValue

转载 作者:行者123 更新时间:2023-12-03 10:14:04 26 4
gpt4 key购买 nike

我有 ComboBoxes在我使用 SelectedValue 选择的 WPF 应用程序中和 SelectedValuePath .有时 SelectedValue不属于 ItemsSource (因为数据库不一致)。

例子:

Items = new ObservableCollection<Item>()
{
new Item() { Id = "1", Text = "Text 1" },
new Item() { Id = "2", Text = "Text 2" },
};

SelectedValue = "3";

ComboBox已加载且未选择其他值, SelectedValue属性仍然是不一致的值(示例中为“3”)。有没有办法让绑定(bind)自动清除 SelectedValue当它不是 ItemsSource 的一部分时?

看法:
<ComboBox ItemsSource="{Binding Items}" 
SelectedValuePath="Id"
SelectedValue="{Binding SelectedValue, Mode=TwoWay}"
DisplayMemberPath="Text" />

View 模型:
public class MainWindowViewModel : ViewModel
{
public MainWindowViewModel()
{
Items = new ObservableCollection<Item>()
{
new Item() {Id ="1", Text = "Text 1" },
new Item() {Id ="2", Text = "Text 2" },
};

SelectedValue = "3";
}

private ObservableCollection<Item> items;

public ObservableCollection<Item> Items
{
get { return items; }
set { items = value; OnPropertyChanged(); }
}

private string selectedValue;

public string SelectedValue
{
get { return selectedValue; }
set { selectedValue = value; OnPropertyChanged(); }
}
}

public class Item
{
public string Id { get; set; }

public string Text { get; set; }

}

最佳答案

这个逻辑应该在 View 模型中实现,即你不应该设置 SelectedValueItems 中没有此类项目时为 3 .然后将 View 模型设置为无效状态。

因此,与其尝试在 View 或控件中实现这种逻辑,不如在它所属的 View 模型中实现它。应该很简单:

SelectedValue = "3";
if (!Items.Any(x => x.Id == SelectedValue))
SelectedValue = null;

或者在 setter 中:
public string SelectedValue
{
get { return selectedValue; }
set
{
selectedValue = value;
if (!Items.Any(x => x.Id == SelectedValue))
selectedValue = null;
OnPropertyChanged();
}
}

关于wpf - 当它不属于 ItemsSource 时,自动从 ComboBox 中清除 SelectedValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43659335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com