Combobox里面的datagrid选中了项目

时间:2011-08-23 13:08:38

标签: silverlight data-binding

我有一个数据网格,它有一列组合框。 数据网格itemssource是UserInfo对象的集合。

以下是UserInfo类的定义:

public class UserInfo
{

    public string User { get; set; }

    public UserRole Role { get; set; }


}
public enum UserRole
{

    None = 0,

    Administrator = 1,

    Reviewer = 2,
}

当我收集集合时,我将其分配给datagrid:

private void svc_GetAllUsersCompleted(object sender, ServiceReference1.GetAllUsersCompletedEventArgs args)
    {
        ObservableCollection<UserInfo> users = args.Result;
        UsersPage.dataGrid1.ItemsSource = users;
    }

这是datagrid的xaml:

<data:DataGrid Margin="5,25,5,17" AutoGenerateColumns="False" AllowDrop="True" Name="dataGrid1"  SelectionMode="Single" UseLayoutRounding="True" SelectionChanged="dataGrid1_SelectionChanged" Grid.RowSpan="2" Grid.ColumnSpan="2" Grid.Row="1" ItemsSource="{Binding}" >
        <data:DataGrid.Resources>
            <DataTemplate x:Key="UserRoleTemplate">
                <Border BorderThickness="0,0,0,0" BorderBrush="#6FBDE8">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>
                        <ComboBox Name="cmbUserRoleTypes" VerticalAlignment="Center" Grid.Column="0" Loaded="cmbUserRoleTypes_Loaded" SelectedIndex="0" ItemsSource="{Binding GetListOfRoles,Source={StaticResource rList}}" SelectedValue="{Binding Role, Mode=TwoWay}" ></ComboBox>
                    </Grid>
                </Border>
            </DataTemplate>
            <DataTemplate x:Key="UserNameTemplate">
                <Border BorderThickness="0,0,0,0" BorderBrush="#6FBDE8">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>
                        <TextBlock Name="txtUserName" VerticalAlignment="Center" Grid.Column="0" Loaded="cmbUserRoleTypes_Loaded" Text="{Binding Path=Name}" ></TextBlock>
                    </Grid>
                </Border>
            </DataTemplate>
        </data:DataGrid.Resources>
        <data:DataGrid.Columns>
            <data:DataGridTextColumn Header="User Name" Width="200"
            Binding="{Binding User}" />
            <data:DataGridTemplateColumn Header="User Role" Width="200"
            CellTemplate="{StaticResource UserRoleTemplate}" />
            <!--<data:DataGridTextColumn Header="Assigned Issues"  />-->
        </data:DataGrid.Columns>
    </data:DataGrid>

使用具有所有用户角色的类中的集合来填充组合:这是xaml:

<UserControl.Resources>
        <local:RolesTypes x:Key="rList">
        </local:RolesTypes>
</UserControl:Resources>

以下是包含该集合的类:

public class RolesTypes
{
    public List<string> GetListOfRoles
    {

        get
        {

            List<string> RolesList = new List<string>();
            RolesList.Add("administrator");
            RolesList.Add("reviewer");
            return RolesList;
        }



    }
}

我的问题是: 组合填充了角色列表,但是当我收到usersinfo集合时,我希望每个用户在其匹配的组合中选择其角色,但不会发生。虽然用户角色DO存在于角色列表中,但在组合中未选择任何角色。 有什么想法吗?

2 个答案:

答案 0 :(得分:1)

CAVEAT:这会使用组合框填充网格,并将组合框设置为用户角色。它是在代码背后完成的,我认为它违反了所有的MVVM主体,但我无法绑定工作。 (也许一些绑定专家可以对此进行修改)也就是说,如果你使用它,你可能应该在组合框中附加一个处理程序,以便在更改组合框时更新用户的角色。希望这有帮助,祝你好运!

修改了cmbUserRoleTypes_Loaded以填充组合框,并删除了转换器代码。请注意,不同的角色值是硬编码的,您可能希望将其设为通用。

修改为包括组合框,抱歉在我不得不离开之前赶紧完成并且没有重新阅读你的帖子。我真的不喜欢它必须在代码隐藏中设置组合框,似乎应该有一些方法来绑定数据。注意:我在将组合框选择绑定到用户记录时遇到问题,但至少会在其中获取填充的组合框。希望它有所帮助。

这是xaml

<UserControl xmlns:data="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  x:Class="StackOverflowProblems.MainPage"
    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:StackOverflowProblems"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Button Content="Populate users" Click="btn_Click" HorizontalAlignment="Left"></Button>
        <StackPanel Grid.Row="1" Orientation="Horizontal">
            <data:Label  Content="Roles:"/>
            <ComboBox VerticalAlignment="Center" Name="myComboBox"  ></ComboBox>
        </StackPanel>
        <Grid Grid.Row="2" x:Name="LayoutRoot" Background="White">
        <data:DataGrid Margin="5,25,5,17" AutoGenerateColumns="False" AllowDrop="True" Name="dataGrid1"  SelectionMode="Single" UseLayoutRounding="True" SelectionChanged="dataGrid1_SelectionChanged" Grid.RowSpan="2" Grid.ColumnSpan="2" Grid.Row="1" ItemsSource="{Binding}" >
            <data:DataGrid.Resources>

                <DataTemplate x:Key="UserRoleTemplate">
                    <Border BorderThickness="0,0,0,0" BorderBrush="#6FBDE8">
                            <ComboBox  VerticalAlignment="Center"  Loaded="cmbUserRoleTypes_Loaded"  >
                                </ComboBox>
                    </Border>
                </DataTemplate>

                <DataTemplate x:Key="UserNameTemplate">
                    <Border BorderThickness="0,0,0,0" BorderBrush="#6FBDE8">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition />
                            </Grid.ColumnDefinitions>
                            <TextBlock Name="txtUserName" VerticalAlignment="Center" Grid.Column="0" Loaded="cmbUserRoleTypes_Loaded" Text="{Binding Path=Name}" ></TextBlock>
                        </Grid>
                    </Border>
                </DataTemplate>
            </data:DataGrid.Resources>

            <data:DataGrid.Columns>
                <data:DataGridTextColumn Header="User Name" Width="200" Binding="{Binding User}" />
                <data:DataGridTemplateColumn Header="User Role" Width="200" CellTemplate="{StaticResource UserRoleTemplate}" />
            </data:DataGrid.Columns>
        </data:DataGrid>

    </Grid>
    </Grid>


</UserControl>

这是背后的代码     使用系统;     使用System.Collections.ObjectModel;     使用System.Reflection;     使用System.Windows;     使用System.Windows.Controls;

    namespace StackOverflowProblems
    {
        public partial class MainPage : UserControl
        {
            ObservableCollection<UserInfo> users = new ObservableCollection<UserInfo>();
            ObservableCollection<string> roles = new ObservableCollection<string>();

            public MainPage()
            {
                InitializeComponent();
                LayoutRoot.DataContext = this;

                InitializeRoles();
            }

            public void InitializeRoles()
            {
                // turn enumeration into a collection of strings
                Type enumType = typeof(UserRole);  

                foreach (FieldInfo fieldInfo in enumType.GetFields(BindingFlags.Public | BindingFlags.Static))  
                {
                    roles.Add(fieldInfo.Name.ToString());
                }

                myComboBox.ItemsSource = roles;
                myComboBox.SelectedIndex = 0;
            }

            public void svc_GetAllUsersCompleted()
            {
                users.Add(new UserInfo("Fred", UserRole.Administrator));
                users.Add(new UserInfo("George", UserRole.None));
                users.Add(new UserInfo("Mary", UserRole.Reviewer));
                dataGrid1.ItemsSource = users;
            }

            private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {

            }

            private void cmbUserRoleTypes_Loaded(object sender, RoutedEventArgs e)
            {
                ComboBox bx = (ComboBox)sender;
                UserInfo ui = (UserInfo)bx.Tag;

                bx.ItemsSource = roles;

                int userRoleIndex = 0;
                switch (ui.Role)
                {
                    case UserRole.None:
                        userRoleIndex = 0;
                        break;
                    case UserRole.Administrator:
                        userRoleIndex = 1;
                        break;
                    case UserRole.Reviewer:
                        userRoleIndex = 2;
                        break;
                    default:
                        throw new Exception("Invalid Role Detected");
                }
                bx.SelectedIndex = userRoleIndex;

            }

            private void btn_Click(object sender, RoutedEventArgs e)
            {
                svc_GetAllUsersCompleted();
            } 

        }
    }

这是支持类文件     使用系统;     使用System.ComponentModel;     使用System.Globalization;     使用System.Windows.Data;

namespace StackOverflowProblems
{
    public class UserInfo : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        private string _User = "";
        public string User
        {
            get { return _User; }
            set
            {
                if (_User != value)
                {
                    _User = value;
                    NotifyPropertyChanged("User");
                }
            }
        }


        private UserRole _Role = UserRole.None;
        public UserRole Role
        {
            get { return _Role; }
            set
            {
                if (_Role != value)
                {
                    _Role = value;
                    NotifyPropertyChanged("User");
                }
            }
        }
        public UserInfo(string user, UserRole role)
        {
            User = user;
            Role = role;
        }
    }

    public enum UserRole
    {

        None = 0,

        Administrator = 1,

        Reviewer = 2,
    }
}

答案 1 :(得分:0)

您的SelectedValue也很有可能在ItemsSource获取GetListOfRoles的值之前接收它的值。

如果我没记错的话,那可能会导致'value'设置为ItemsSource中不存在的项目的问题。