簡體   English   中英

將ComboBox SelectedItem綁定到Datagrid

[英]Binding ComboBox SelectedItem to Datagrid

在數據網格中顯示字符串時遇到一些問題。

解釋代碼:我將士兵集合綁定到ComboBox。 士兵有自己的武器收藏。

當我在“組合框”中選擇特定士兵時,我希望該士兵的武器顯示在數據網格中。 我相信綁定正確,但是datagrid總是空白。 有人知道我在做什么錯嗎?

XAML

<Grid>
    <ComboBox x:Name="Character_ComboBox" HorizontalAlignment="Left" VerticalAlignment="Top" Width="328" Height="25">
    </ComboBox>
</Grid>

<DataGrid x:Name="Character_items_datagrid" ItemsSource="{Binding ElementName=Character_ComboBox, Path= SelectedItem.Equipment, Mode=OneWay}" Margin="328,0,0,0" Grid.RowSpan="2" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="Primary"  Binding="{Binding Primary, Mode=TwoWay}" FontWeight="Bold" Foreground="Black" Width="0.1*"></DataGridTextColumn>
        <DataGridTextColumn Header ="Secondary" Binding="{Binding Secondary, Mode=TwoWay}" Width="0.1*"></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

士兵級

public class Soldier 
{
    public string Soldier_Class { get; set; }
    public ObservableCollection<Weapons> Equipment { get; set; }
}

武器課

public class Weapons
{
    string Primary { get; set; }
    string Secondary { get; set; }

    public Weapons(string primary, string secondary)
    {
        this.Primary = primary;
        this.Secondary = secondary;
    }
}

主窗口

public ObservableCollection<Soldier> squad_members = new ObservableCollection<Soldier>();

public MainWindow()
{
    InitializeComponent();

    squad_members.Add(new Soldier() { Soldier_Class = "Assult Soldier", Equipment = new ObservableCollection<Weapons>() { new Weapons("M4 Rifle", "Compact 45 Pistol")}});
    squad_members.Add(new Soldier() { Soldier_Class = "SMG Soldier", Equipment = new ObservableCollection<Weapons>() { new Weapons("RPK Machine Gun", "HK Shotgun"), new Weapons("SAW Machine Gun", "Compact 45 Pistol")}});
    squad_members.Add(new Soldier() { Soldier_Class = "Juggernaut", Equipment = new ObservableCollection<Weapons>() { new Weapons("MP5", "Bowie Knife") }});

    Binding comboBinding = new Binding();
    comboBinding.Source = squad_members;

    BindingOperations.SetBinding(Character_ComboBox, ComboBox.ItemsSourceProperty, comboBinding);
    Character_ComboBox.DisplayMemberPath = "Soldier_Class";
    Character_ComboBox.SelectedValuePath = "Soldier_Class";
}

結果:

在此處輸入圖片說明

您需要public模型中的屬性以進行綁定才能起作用:

public class Weapons
{
    public string Primary { get; set; }
    public string Secondary { get; set; }
    .....
}

您的DataGrid看起來正確填充了項目,只是每個項目的屬性未正確顯示在列中。 這表明綁定引擎由於其private可訪問性而無法訪問該項目的屬性。

如har07所寫,您的主要問題是公共訪問修飾符。

您還可以改善許多其他方面。 為您的類實現INotifyPropertyChanged ,因此對屬性的任何更改都將立即由UI反映出來。 沒有令人信服的理由,請勿在代碼中創建綁定。 使用ViewModel進行綁定,而不是直接綁定到ComboBox.SelectedItem元素。 如果要設置列樣式,請將AutoGenerateColumns設置為false(您的代碼將產生四列)。 使用Grid.ColumnDefinitions而不是分配固定的邊距。

楷模:

using System.Collections.ObjectModel;
using System.ComponentModel;

namespace WpfApplication1.ViewModels
{
    public class SquadViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private ObservableCollection<Soldier> _squadMembers;
        public ObservableCollection<Soldier> SquadMembers { get { return _squadMembers; } set { _squadMembers = value; OnPropertyChanged("SquadMembers"); } }

        private Soldier _selectedSoldier;
        public Soldier SelectedSoldier { get { return _selectedSoldier; } set { _selectedSoldier = value; OnPropertyChanged("SelectedSoldier"); } }


        public SquadViewModel()
        {
            SquadMembers = new ObservableCollection<Soldier>()
            {
                new Soldier() { SoldierClass = "Assult Soldier", Equipment = new ObservableCollection<Weapon>() { new Weapon("M4 Rifle", "Compact 45 Pistol") } },
                new Soldier() { SoldierClass = "SMG Soldier", Equipment = new ObservableCollection<Weapon>() { new Weapon("RPK Machine Gun", "HK Shotgun"), new Weapon("SAW Machine Gun", "Compact 45 Pistol") } },
                new Soldier() { SoldierClass = "Juggernaut", Equipment = new ObservableCollection<Weapon>() { new Weapon("MP5", "Bowie Knife") } }
            };
        }
    }

    public class Soldier : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private string _soldierClass;
        public string SoldierClass { get { return _soldierClass; } set { _soldierClass = value; OnPropertyChanged("SoldierClass"); } }

        private ObservableCollection<Weapon> _equipment;
        public ObservableCollection<Weapon> Equipment { get { return _equipment; } set { _equipment = value; OnPropertyChanged("Equipment"); } }
    }

    public class Weapon : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private string _primary;
        string Primary { get { return _primary; } set { _primary = value; OnPropertyChanged("Primary"); } }

        private string _secondary;
        string Secondary { get { return _secondary; } set { _secondary = value; OnPropertyChanged("Secondary"); } }

        public Weapon(string primary, string secondary)
        {
            this.Primary = primary;
            this.Secondary = secondary;
        }
    }
}

XAML:

<Window x:Class="WpfApplication1.MainWindow"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:vm="clr-namespace:WpfApplication1.ViewModels"
                Title="MainWindow" Height="350" Width="580">

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

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <ComboBox x:Name="CbxCharacter" HorizontalAlignment="Left" VerticalAlignment="Top" Width="328" Height="25"
                  ItemsSource="{Binding SquadMembers}" SelectedItem="{Binding SelectedSoldier}"
                  DisplayMemberPath="SoldierClass" SelectedValuePath="SoldierClass"/>

        <DataGrid x:Name="DgCharacterItems" ItemsSource="{Binding SelectedSoldier.Equipment, Mode=OneWay}" Grid.Column="1" AutoGenerateColumns="False"  >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Primary" Binding="{Binding Primary, Mode=TwoWay}" FontWeight="Bold" Foreground="Black" Width="*" />
                <DataGridTextColumn Header="Secondary" Binding="{Binding Secondary, Mode=TwoWay}" Width="*" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM