【问题标题】:ComboBox binding to SelectedValue does not workComboBox 绑定到 SelectedValue 不起作用
【发布时间】:2016-06-17 06:46:49
【问题描述】:

我需要将 ComboBox 绑定到枚举值,并遵循了一些想法。我最终找到了我能找到的最简单的解决方案,它应该满足我的所有需求,除了它不能完全工作,但它应该......

这是我正在做的事情: 我需要 DataGrid 单元格中的 ComboBox,所以我为此定义了一个 DataGridTemplateColumn

<DataGridTemplateColumn MinWidth="150" Header="Data-Type">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ComboBox SelectedValue="{Binding SelectedDataType,Mode=TwoWay}" ItemsSource="{Binding DataTypeValues}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

在我的 ViewModel 中填充枚举值

public IEnumerable<MyType> DataTypeValues
{
    get
    {
        return Enum.GetValues(typeof(MyType)).Cast<MyType>().ToList<MyType>();
    }
}

并且具有所选值的属性

MyType _selectedType;
public MyType SelectedDataType
{
    get { return _selectedType; }
    set
    {
        _selectedType = value;
        OnPropertyChanged();
    }
}

ComboBox 按我的预期填充了我的枚举值,但是当我选择另一个值时,不会调用 SelectedDataType 的设置器,这意味着我不知道当前选择了哪个项目。我也尝试使用 SelectedItem 绑定而不是 SelectedValue,但这也不起作用。

我在这里缺少什么?

编辑:错字

编辑2: --------更新--------

现在我创建了一个示例 WPF 应用程序来重现我的问题。只使用了那里的相关代码部分,并且存在同样的问题。以下是该示例的完整源代码:

Xaml 文件:

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication2"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid ItemsSource="{Binding Parameters}" AutoGenerateColumns="False" SelectedItem="{Binding SelectedParameter, Mode=TwoWay}">
        <DataGrid.Columns>
            <DataGridTemplateColumn MinWidth="150" Header="Data-Type">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox ItemsSource="{Binding DataTypeValues}" SelectedItem="{Binding SelectedType, Mode=TwoWay}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

还有.cs文件:

namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        var vm = new Viewmodel();
        DataContext = vm;
    }
}

class Viewmodel : ViewModelBase
{
    public Viewmodel()
    {
        Parameters = new ObservableCollection<Parameter>();
        Parameters.Add(new Parameter());
    }

    public ObservableCollection<Parameter> Parameters
    {
        get; private set;
    }

    public Parameter SelectedParameter { get; set; }
}

class Parameter : ViewModelBase
{
    MyType _selectedType;
    public MyType SelectedType
    {
        get { return _selectedType; }
        set
        {
            _selectedType = value;
            OnPropertyChanged();
        }
    }

    public IEnumerable<MyType> DataTypeValues
    {
        get { return Enum.GetValues(typeof(MyType)).Cast<MyType>(); }
    }
}

public enum MyType
{
    INT,
    DOUBLE,
    REAL,
    STRING
}

public class ViewModelBase : INotifyPropertyChanged
{
    protected virtual void OnPropertyChanged(bool validateFields = true, [CallerMemberName] string propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
}

【问题讨论】:

  • 我尝试了更多变体,但似乎问题在于 DataGrid 中 ComboBox 的使用。当我在应用程序的另一部分使用 ComboBox 时,上面的 viewmodel 代码可以很好地工作。但是,当我定义 DataGridColumn 的 CellTemplate 并在那里使用 ComboBox 以及后面发布的代码时,与所选值的绑定不像描述的那样工作......有什么想法吗?我的 XAML 出了什么问题?
  • 现在检查。我已经更新了答案。它在我这边工作正常。

标签: c# wpf combobox enums


【解决方案1】:

我认为您正在将所选项目绑定到窗口视图模型中,在 datagrid 中进行绑定。下面的代码对我有用。

XAML:

 <DataGrid Name="datagrid" ItemsSource="{Binding List,Mode=TwoWay}"   >
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Status" Width="100">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox Height="22" 
                                     ItemsSource="{Binding DataContext.DataTypeValues,RelativeSource={RelativeSource AncestorType=Window,
                                                                                        AncestorLevel=1}}"
                                      SelectedItem="{Binding SelectedDataType,UpdateSourceTrigger=PropertyChanged}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>               

                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>

视图模型:

 private List<ListItems> list;

        public List<ListItems> List
        {
            get { return list; }
            set
            {
                list = value;
                this.NotifyPropertyChanged("List");
            }
        }

        public IEnumerable<MyType> DataTypeValues
        {
            get
            {
                return Enum.GetValues(typeof(MyType)).Cast<MyType>().ToList<MyType>();
            }
        }

        public ViewModel()
        {
            List = new List<ListItems>();
            List.Add(new ListItems());
            List.Add(new ListItems());

        }

网格项目:

public class ListItems 
    {

        MyType _selectedType;
        public MyType SelectedDataType
        {
            get { return _selectedType; }
            set
            {
                _selectedType = value;
                this.NotifyPropertyChanged("SelectedDataType");
            }
        }
    }

【讨论】:

    【解决方案2】:

    **编辑:**

    是的,我现在遇到了问题。您的代码不起作用,因为正在绑定 SelectedValue

    改为绑定SelectedItem 属性并检查。它应该可以工作。

    <DataGridTemplateColumn MinWidth="150" Header="Data-Type">
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <ComboBox SelectedItem="{Binding SelectedDataType,Mode=TwoWay}" ItemsSource="{Binding DataTypeValues}"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    

    【讨论】:

    • 感谢您的建议。我现在试过了,但结果还是一样。我将值放入 ComboBox,但与 SelectedItem 或 SelectedValue 的绑定也不适用于该方法:-/
    • 现在检查。我已经更新了答案。它在我这边工作正常。
    • 你检查了吗
    • 是的,我做到了。正如您在我更新的问题中看到的那样,我提供了一个对我不起作用的完整示例。我已经使用了你的建议并绑定到 SelectedItem。我发布的示例代码对您有用吗?那肯定是我的安装有问题或者别的什么的……
    【解决方案3】:

    您应该在绑定到 selectedvalue 属性或 selectedItem 时使用元素名称

     <DataTemplate>
                            <ComboBox Height="22" 
                                     ItemsSource="{Binding DataContext.DataTypeValues,RelativeSource={RelativeSource AncestorType=Window,
                                                                                        AncestorLevel=1}}"
                                      SelectedItem="{Binding SelectedDataType,ElementName="datagrid",UpdateSourceTrigger=PropertyChanged}"/>
                        </DataTemplate>
    

    【讨论】:

    • 不明白...该绑定应该如何工作...将我的 ComboBox 的 SelectedItem 绑定到父 DataGrid SelectedItem。对我来说毫无意义......
    • 抱歉回复晚了,但是,当您将组件与父组件的数据上下文绑定时,这对我有用,然后子组件将自动继承父组件的数据上下文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2010-09-30
    • 2019-02-12
    • 2010-10-14
    • 2015-08-23
    • 2012-06-23
    • 2011-04-17
    相关资源
    最近更新 更多