Gam*_*a11 2 c# data-binding wpf xaml combobox
我有一个ComboBoxwhoSelectedItem和ItemsSource数据绑定到视图模型。每当"Blue"被选中时,setter 都会设置值"Green"并触发PropertyChanged事件。
我期望的ComboBox,以显示"Green"在这种情况下,而不是显示值遗体"Blue"。
我已经尝试了相同的CheckBox(bind to IsChecked,false只要它设置为true和 fire就将值恢复为PropertyChanged),并且它在那里按预期工作。
MainWindow.xaml:
<Window x:Class="WpfTestApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="80" Width="100">
<Grid>
<ComboBox x:Name="ComboBox" SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding Values}" />
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
MainWindow.xaml.cs:
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
namespace WpfTestApplication
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ComboBox.DataContext = new ViewModel();
}
}
public class ViewModel : INotifyPropertyChanged
{
public List<string> Values { get; set; } = new List<string>
{
"Green", "Red", "Blue"
};
public string SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
if (selectedItem == "Blue")
selectedItem = "Green";
SelectedItemChanged();
}
}
private string selectedItem = "Red";
public event PropertyChangedEventHandler PropertyChanged;
public void SelectedItemChanged() =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedItem)));
}
}
Run Code Online (Sandbox Code Playgroud)
这确实有点奇怪。事实证明,即使组合框显示“蓝色”,它SelectedItem现在声称是预期的“绿色”。我不知道为什么显示的值和可通过编程访问的SelectedItem值之间存在差异,但我确实找到了解决方法:
<ComboBox
VerticalAlignment="Top"
x:Name="ComboBox"
SelectedItem="{Binding SelectedItem, Delay=1}"
ItemsSource="{Binding Values}" />
Run Code Online (Sandbox Code Playgroud)
这样Delay做的技巧,所以这里肯定有一些时间问题。
我试图创建一个适当的依赖属性,希望值强制能够解决问题:
public sealed partial class MainWindow
{
private static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register(
"SelectedItem",
typeof(string),
typeof(MainWindow),
new PropertyMetadata("Red", SelectedItemChanged, SelectedItemCoerceValue));
private static void SelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
private static object SelectedItemCoerceValue(DependencyObject d, object basevalue)
{
if ("Blue".Equals(basevalue))
{
return "Green";
}
return basevalue;
}
public List<string> Values { get; set; } = new List<string>
{
"Green", "Red", "Blue",
};
public MainWindow()
{
InitializeComponent();
ComboBox.DataContext = this;
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,那个也需要Delay属性集。
| 归档时间: |
|
| 查看次数: |
699 次 |
| 最近记录: |