C# WPF 将字典绑定到列表视图

本文关键字:列表 视图 绑定 字典 WPF | 更新日期: 2023-09-27 17:57:13

我正在使用我的第一个更大的WPF程序,许多Windows和ViewModel,到目前为止,我可以帮助自己。
起初我有 2 个列表,一个List<double> Factor,一个List<string> Name,我试图将两者绑定到一个列表视图。它没有用,我认为字典会更好。

所以现在我有了一个Dictionary<string, double> IngList = new Dictionary<string, double>(); 单击按钮后,2 文本框的内容应添加到字典中,然后显示在我的列表视图中。

(只是代码的一小部分,否则会占用很多空间)

我的视图模型:

namespace FoodsLib.ViewModel
{
    public class ViewModelAddRecipeWindow : ViewModelBase, INotifyPropertyChanged
    {
        public ViewModelAddRecipeWindow( IViewControl vctrl) 
        {
                AddIngredientCmd = new RelayCommand(() => AddToList() 
                _viewControl = vctrl;
                }
        }
        protected IViewControl _viewControl;

   new public event PropertyChangedEventHandler PropertyChanged;
        new protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }
        protected string _ingredientR, _name, _stringtype, _stringCategory, _recipe;
            public double Factor
            {
                get { return _factor; }
                set
                {
                    if (_factor != value)
                    {
                        _factor = value;
                        OnPropertyChanged("Factor");
                    }
                }
            }
            public string IngredientR
            {
                get { return _ingredientR; }
                set
                {
                    if (_ingredientR != value)
                    {
                        _ingredientR = value;
                        this.OnPropertyChanged("IngredientR");
                    }
                }
            }
            Dictionary<string, double> IngList = new Dictionary<string, double>();

    public void AddToList()
            {
                if (!IngList.ContainsKey(IngredientR))
                {
                    IngList.Add(IngredientR, Factor);
                    _viewControl.ShowMessage("Added", "Ingredient");
                }
                else
                {
                    _viewControl.ShowMessage("You can't add an Ingredient twice", "Ingredient Error.");
                    return;
                }
            }
        public ICommand AddIngredientCmd { get; set; }
      }
}

我的观点是:

 <Grid Grid.Row="2" Grid.Column="3" HorizontalAlignment="Left" 
                  Margin="5,5,5,5" Grid.ColumnSpan="2" Grid.RowSpan="6">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100"></ColumnDefinition>
                    <ColumnDefinition Width="240"></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <TextBox x:Name="tbAddFood" Grid.Row="0" Grid.Column="1" Text="{Binding IngredientR, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"  
                     Width="160" Margin="5" HorizontalAlignment="Left"/>
                <TextBox x:Name="tbAddFoodAmount" Grid.Row="1" Grid.Column="1" Text="{Binding Factor, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  
                     Width="50" Margin="5" HorizontalAlignment="Left"/>
                <Label Grid.Row="0" Grid.Column="0" Content="Ingredients"  HorizontalAlignment="Right"
                   Margin="5" Foreground="#ebeff4"/>
                <Label Grid.Row="1" Grid.Column="0" Content="Amount"  HorizontalAlignment="Right"
                   Margin="5" Foreground="#ebeff4"/>

                <Button x:Name="btAddIngredient" Grid.Row="1" Grid.Column="1"
                Command="{Binding Path=AddIngredientCmd}" Content=" Add "  Margin="5,5,30,5" 
                    BorderBrush="#415578" BorderThickness="0" 
                    HorizontalAlignment="Center" Background="#415578" Foreground="#ebeff4"/>
                <ListView x:Name="lbFoodList" Grid.Column="1" Grid.Row="2"  Margin="5" Height="120" VerticalAlignment="Top"
                         Foreground="#ebeff4" ItemsSource="{Binding IngList}"
                                         ScrollViewer.VerticalScrollBarVisibility="Visible" Grid.RowSpan="4">
                    <ListView.View>
                        <GridView>
                            <GridView.ColumnHeaderContainerStyle>
                                <Style>
                                    <Setter Property="FrameworkElement.Visibility" Value="Collapsed"/>
                                </Style>
                            </GridView.ColumnHeaderContainerStyle>
                            <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Key, Mode=OneWay}"></GridViewColumn>
                            <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Value, Mode=OneWay}"></GridViewColumn>
                        </GridView>
                    </ListView.View>
                </ListView>
            </Grid>

我到了字典被这两个项目填满的地步,但 ListView 不会显示任何内容。

我不是在要求一个完整的代码,只是一个"如何"和"为什么"。泰

编辑:

使用ObservableCollection可以解决问题。

public ObservableCollection<tempIng> _ListMF = new
ObservableCollection<tempIng>();
        public ObservableCollection<tempIng> ListMF
        {
            get { return _ListMF; }
            set { _ListMF = value; OnPropertyChanged("_ListMF"); }
        }

使用新的类临时,单击"添加"后获取名称和因子。

public class tempIng
{
    public string Name { get; set; }
    public double Factor { get; set; }
    public override string ToString()
    {
        return this.Name + ", " + this.Factor ;
    }
}

Ty,我在.xaml中设置了DataContext.cs
它也适用于列表吗?

C# WPF 将字典绑定到列表视图

只能绑定到属性。尝试将您的列表设为

public ObservableCollection<KeyValuePair> IngList { get; private set; }

我也没有看到您设置数据上下文,所以如果这听起来很新,这里也是一个示例。

   <Control>
    <Control.Resources>
        <ViewmodelNamespace:ViewModelAddRecipeWindow x:Key="ReceipieViewModel"/>
    </Control.Resources>
    <Grid DataContext="{StaticResource ReceipieViewModel}">
        <ListView ItemsSource="{Binding IngList}"/>
    </Grid>
  </Control>

下面是有关绑定到 WPF 中的列表的教程