将DatagridColumn绑定到指向WPF中ObservableCollection的StaticResource

本文关键字:ObservableCollection StaticResource WPF DatagridColumn 绑定 | 更新日期: 2023-09-27 18:26:19

在GridView中,可以手动将列ItemsSource绑定到Enum,selectedItemBinding路径设置为DataGrid.ItemsSource的属性,如下所示:

<Window.Resources>
<ObjectDataProvider x:Key="DirectionEnum"
                    MethodName="GetValues"
                    ObjectType="{x:Type core:Enum}">
        <ObjectDataProvider.MethodParameters>
                <x:Type Type="local:Direction"/>
        </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>

<DataGrid x:Name="DgvZlecNag" 
    AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridComboBoxColumn Header="Column0"
                 SelectedItemBinding="{Binding Direction}"
                 ItemsSource="{Binding Source={StaticResource DirectionEnum}}"/>

public enum Direction 
{
    Def = 0,
    Imp = 1,
    Exp = 2,
}

public MainWindow()
    {
        InitializeComponent();
        _orders = new ObservableCollection<ZlecNag>()
        {
            new ZlecNag() {
                Id = 1,
                Direction = Direction.Imp
                }
        }
    DgvZlecNag.ItemsSource = zlecenia;
    }

我想做的是类似地将列绑定到ObservableCollection,但它并没有完全起作用。我试着用column1中的staticResource来做这件事,它可以工作,但不会显示初始设置的值,和第2列中的局部observableCollection,它显示了初始值,但绑定属性的值不会随着在组合框中选择新项而改变。第3列只是显示绑定的属性是否更改。

<Window x:Class="ZleceniaTransportowe2.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:ZleceniaTransportowe2"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:core="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        Title="MainWindow" Height="500" Width="1200"
        >
<Window.Resources>
       <ObjectDataProvider x:Key="Clients"
                            MethodName="GetData"
                            ObjectType="{x:Type local:CollectionData}"
                            >
            <ObjectDataProvider.MethodParameters>
                <x:Type Type="local:CollectionData"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
        <local:IfNullConverter x:Key="IfNullConverter"/>
</Window.Resources>
        <DataGrid x:Name="DgvZlecNag" 
                  AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id"
                                    Binding="{Binding Id, Mode=OneWay}"/>
                <DataGridComboBoxColumn Header="Column1"
                                        SelectedItemBinding="{Binding Path=Client, Mode=TwoWay}"
                                        ItemsSource="{Binding Source={StaticResource Clients}}"
                                        SelectedValuePath="Akronim"  DisplayMemberPath="Akronim"/>
                <DataGridTemplateColumn Header="Column2">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox SelectedValue="{Binding Client.Akronim, Mode=TwoWay}"
                                      DisplayMemberPath="Akronim"  SelectedValuePath="Akronim" SelectedItem="Client"
                                      ItemsSource= "{Binding Clients, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window }}}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="column3"
                                    Binding="{Binding Client.Akronim, Mode=OneWay}"/>
            </DataGrid.Columns>
        </DataGrid>
</Window>

背后的代码:

namespace ZleceniaTransportowe2
{
    public partial class MainWindow: Window
    private ObservableCollection<ZlecNag> _orders;
    public ObservableCollection<Client> Clients {get;} = new ObservableCollection<Client>()
        {
            new Client()
            {
                Akronim = "Seifert",
            },
            new Client()
            {
                Akronim = "Cenergo",
            }
        };
        public MainWindow()
        {
            InitializeComponent();
            _orders = new ObservableCollection<ZlecNag>()
            {
                new ZlecNag() {
                    Id = 1,
                    Client = Clients.First(),
                },
               new ZlecNag() {
                    Id = 1,
                    Client = Clients[1],
                   }
                };
             DgvZlecNag.ItemsSource = _orders;
        }
    }
}

public class ZlecNag : INotifyPropertyChanged
{
    private Direction _direction;
    private Client _client;
    public Direction Direction
    {
        get { return _client; }
        set
        {
            _direction= value;
            OnPropertyChanged();
        }
    }
    public Client Client
    {
        get { return _client; }
        set
        {
            _client = value;
            OnPropertyChanged();
        }
    }
        public event PropertyChangedEventHandler PropertyChanged;
    [NotifyPropertyChangedInvocator]
    void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class Client : INotifyPropertyChanged
{
    private int _gidNumer;
    private string _akronim;
    public int GidNumer
    {
        get { return _gidNumer; }
        set
        {
            _gidNumer = value;
            OnPropertyChanged();
        }
    }
    public string Akronim
    {
        get { return _akronim; }
        set
        {
            _akronim = value;
            OnPropertyChanged();
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    [NotifyPropertyChangedInvocator]
    void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

使用第2列的objectDataProvider的数据类:

public class CollectionData
{
    public static ObservableCollection<Client> GetData(Type type = null)
    {
        var clients = new ObservableCollection<Client>()
        {
            new Client()
            {
                Akronim = "Seifert",
                GidNumer = 4654
            },
              new Kontrahent()
            {
                Akronim = "Cenergo",
                GidNumer = 4656
            }
        };
        return clients;
    }
}

请帮忙,我不知道如何解决这个问题。

将DatagridColumn绑定到指向WPF中ObservableCollection的StaticResource

您没有在column2中使用Binding,而是编写了SelectedItem="Client",请考虑在SelectedItem中进行绑定。

显然,在没有包含combobox的模板列的情况下也可以实现。它看起来更好,因为单元格在被点击之前看起来不像一个组合框,所以它不会从其他DataGrid单元格中脱颖而出。

基于答案https://stackoverflow.com/a/5409984/2458980

<DataGridComboBoxColumn SelectedValueBinding="{Binding Contractor, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                        DisplayMemberPath="Acronym">     
    <DataGridComboBoxColumn.ElementStyle>
         <Style TargetType="{x:Type ComboBox}">
             <Setter Property="ItemsSource" Value="{Binding Path=Contractors, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
         </Style>
     </DataGridComboBoxColumn.ElementStyle>
     <DataGridComboBoxColumn.EditingElementStyle>
         <Style TargetType="{x:Type ComboBox}">
             <Setter Property="ItemsSource" Value="{Binding Path=Contractors, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
         </Style>
     </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>