c# - 在 setter 中更改 SelectedItem 值对 ComboBox 没有影响

标签 c# wpf xaml data-binding combobox

我有一个 ComboBox谁的SelectedItemItemsSource数据绑定(bind)到 View 模型。每当"Blue"被选中时,setter 改为设置值 "Green"并触发 PropertyChanged事件。

我希望 ComboBox显示 "Green"在这种情况下,显示的值仍然是 "Blue" .

我用 CheckBox 试过同样的方法(绑定(bind)到 IsChecked ,将值恢复为 false 每当它设置为 true 并触发 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>

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)));
    }
}

最佳答案

这确实有点奇怪。事实证明,即使组合框显示“蓝色”,它的 SelectedItem 现在声称是预期的“绿色”。我不知道为什么显示的值与编程可访问的 SelectedItem 值之间存在差异,但我确实找到了解决方法:

<ComboBox
    VerticalAlignment="Top"
    x:Name="ComboBox"
    SelectedItem="{Binding SelectedItem, Delay=1}"
    ItemsSource="{Binding Values}" />

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;
    }
}

不幸的是,那个还需要 Delay 属性集。

关于c# - 在 setter 中更改 SelectedItem 值对 ComboBox 没有影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34286342/

相关文章:

c# - UserControl 依赖属性设计时

c# - 'Windows.Storage.StorageFile File = await FilePicker.PickSingleFileAsync()' 不工作

wpf - 是否可以参数化资源中 DataGrid CellTemplate 上的绑定(bind)?

c# - 将值舍入到最接近的 2 的幂

c# - 将 header 添加到操作请求和响应

c# - 在 WPF 中拖放图像

c# - MVVM:如何对控件进行函数调用?

c# - 未触发 Focused 或 OnFocusChange 事件

c# - 是否可以在局部 View 中加载局部 View ?

c# - 为什么 is 关键字需要非空表达式?