简体   繁体   English

如何从ListView绑定组合框的SelectedItem / Value / ValuePath

[英]How to bind a Combobox's SelectedItem/Value/ValuePath from within a ListView

I have a ComboBox inside of a ListView 's GridView . 我在ListViewGridView有一个ComboBox I am unable to get the ItemsSource and SelectedItem/Value/ValuePath bindings correct. 我无法正确获得ItemsSource和SelectedItem / Value / ValuePath绑定。 Below is the smallest complete example demonstrating my problem: 以下是展示我的问题的最小的完整示例:

Test_ComboBox_Binding.Views: Test_ComboBox_Binding.Views:

<Window x:Class="Test_ComboBox_Binding.Views.UserView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:system="clr-namespace:System;assembly=mscorlib"
        xmlns:m="clr-namespace:Test_ComboBox_Binding.Models"
        xmlns:vm="clr-namespace:Test_ComboBox_Binding.ViewModels"
        xmlns:s="clr-namespace:Test_ComboBox_Binding.Shared"
        Title="UserView" Height="300" Width="300">

    <Window.DataContext>
        <vm:UserViewModel/>
    </Window.DataContext>

    <Window.Resources>
        <DataTemplate x:Key="NameCellTemplate" DataType="m:cUser">
            <TextBlock Text="{Binding Name}"></TextBlock>
        </DataTemplate>       
        <DataTemplate x:Key="FavoriteColorCellTemplate" DataType="m:cUser">
            <ComboBox ItemsSource="{Binding Colors, RelativeSource={RelativeSource AncestorType=vm:UserViewModel}}"
                      SelectedValue="{Binding FavoriteColor}"
                      SelectedValuePath="{Binding FavoriteColor}"
                      MinWidth="60"/>
        </DataTemplate>        
    </Window.Resources>

    <Grid>
        <ListView ItemsSource="{Binding Users}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" Width="100" CellTemplate="{StaticResource NameCellTemplate}"></GridViewColumn>
                    <GridViewColumn Header="Favorite Color" Width="100" CellTemplate="{StaticResource FavoriteColorCellTemplate}"></GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>    
    </Grid>
</Window>

Test_ComboBoxBinding.ViewModels: Test_ComboBoxBinding.ViewModels:

using System.Collections.Generic;
using System.Collections.ObjectModel;
using Test_ComboBox_Binding.Models;
using Test_ComboBox_Binding.Shared;

namespace Test_ComboBox_Binding.ViewModels
{
    class UserViewModel : cINotifyPropertyChangedBase
    {
        private ObservableCollection<ColorEnum> _colors;
        public ObservableCollection<ColorEnum> Colors
        {
            get { return _colors; }
            set { _colors = value; OnPropertyChanged("Colors"); }
        }

        private ObservableCollection<cUser> _users;
        public ObservableCollection<cUser> Users
        {
            get { return _users; }
            set { _users = value; OnPropertyChanged("Users");}
        }

        public UserViewModel()
        {
            Colors = new ObservableCollection<ColorEnum>(){ColorEnum.Red, ColorEnum.White, ColorEnum.Blue};

            List<cUser> userList = new List<cUser>();
            userList.Add(new cUser("Jack", Colors[0]));
            userList.Add(new cUser("Jill", Colors[1]));
            userList.Add(new cUser("James", Colors[2]));
            Users = new ObservableCollection<cUser>(userList);
        }
    }
}

Test_ComboBox_Binding.Models: Test_ComboBox_Binding.Models:

using System.ComponentModel;
using Test_ComboBox_Binding.Shared;
using Test_ComboBox_Binding.ViewModels;

namespace Test_ComboBox_Binding.Models
{
    class cUser : cINotifyPropertyChangedBase
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; OnPropertyChanged("Name"); }
        }

        private ColorEnum _favoriteColor;
        public ColorEnum FavoriteColor
        {
            get { return _favoriteColor; }
            set { _favoriteColor = value; OnPropertyChanged("FavoriteColor"); }
        }

        public cUser(string name, ColorEnum favoriteColor)
        {
            Name = name;
            FavoriteColor = favoriteColor;
        }
    }
}

Test_ComboBox_Binding.Shared: Test_ComboBox_Binding.Shared:

namespace Test_ComboBox_Binding.Shared
{
    public enum ColorEnum
    {
        Red,
        White,
        Blue
    }
}

Running the above code will produce the image below - a ListView with a ComboBox that contains the enumerated ItemsSource correctly, yet not displaying the SelectedValue for each cUser : 运行上面的代码将产生下面的图像-一个带有ComboBoxListView ,该ComboBox正确包含枚举的ItemsSource ,但未显示每个cUserSelectedValue

在此处输入图片说明

Please educate me on how to get the ItemsSource and SelectedItem/Value/ValuePath set correctly. 请教我如何正确设置ItemsSource和SelectedItem / Value / ValuePath。 I have scoured the interweb for informations and am unable to solve this problem. 我已经在Internet上搜索了有关信息,无法解决此问题。 I must be missing some key understanding. 我一定缺少一些关键的理解。 Thank you! 谢谢!

I believe your problem is you're setting FavoriteColor to a different referenced object than the one produced by the dataprovider binding. 我相信您的问题是您将FavoriteColor设置为与dataprovider绑定产生的对象不同的引用对象。 Try exposing a collection of Enums in the UserViewModel, binding your combobox to that collection (you may need to use FindAncestor to access it), and then using a reference from that collection to set favorite color initially. 尝试在UserViewModel中公开一个Enums集合,将组合框绑定到该集合(您可能需要使用FindAncestor来访问它),然后使用该集合中的引用来初始设置喜欢的颜色。

The AncestorType of a RelativeSource refers to the type of element in the visual tree. RelativeSourceAncestorType引用可视化树中元素的类型。 You could set it to ListBox and then bind to the Colors property of the DataContext of the ListBox , which is your view model. 您可以将其设置为ListBox ,然后绑定到您的视图模型ListBoxDataContextColors属性。

You should also bind the SelectedItem property to the FavoriteColor source property. 您还应该将SelectedItem属性绑定到FavoriteColor源属性。 This should work: 这应该工作:

<DataTemplate x:Key="FavoriteColorCellTemplate" DataType="m:cUser">
    <ComboBox ItemsSource="{Binding DataContext.Colors, RelativeSource={RelativeSource AncestorType=ListBox}}"
              SelectedItem="{Binding FavoriteColor}"
              MinWidth="60"/>
</DataTemplate>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从另一个DataContext绑定ComboBox SelectedItem? - How to bind ComboBox SelectedItem from another DataContext? 如何将不同的属性绑定到ComboBox的SelectedItem和SelectedIValue? - How to bind different properties to SelectedItem and SelectedIValue of ComboBox? 如何将Combobox绑定到带有ListBox依赖的SelectedItem的ObservableCollection? - How to bind a Combobox to an ObservableCollection with SelectedItem dependant on ListBox? 如何在ComboBox中将ItemSource和SelectedItem与字符串绑定? - How to bind the ItemSource and SelectedItem with String in ComboBox? C# - 如何从特定值设置ComboBox selectedItem? - C# - How to set a ComboBox selectedItem from specific value? listview和combobox的SelectedItem颜色 - SelectedItem color of listview and combobox 通过字段的值绑定Combobox SelectedItem - Binding Combobox SelectedItem by a field's value 来自 GridView 控件的 UWP 组合框 SelectedItem 以及使用 MVVM 模式将选择更改值绑定到模型 - UWP Combobox SelectedItem from GridView Control and also Bind selection change value to model with MVVM Pattern WPF MVVM 如何将 ComboBox SelectedItem 绑定到特定的 DataGrid 选定行列值 - WPF MVVM How to bind ComboBox SelectedItem to specific DataGrid selected row column value 如何在 Telerik 的 RadCartesianChart 的工具提示中显示不受 CategoryPath 或 ValuePath 约束的值? - How to show a value which is not bound by the CategoryPath or ValuePath inside the Telerik's RadCartesianChart's Tooltip?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM