繁体   English   中英

WPF:comboBox数据绑定问题

[英]WPF: comboBox data binding issue

我有一个public class LPosition ,它包含一个属性public String OZ { get; set; } public String OZ { get; set; } public String OZ { get; set; } 应用程序读取.txt和.xml文件,OZ从这些文件中获取值。 我需要将OZ绑定到comboBox:

<ComboBox x:Name="OZs" SelectionChanged="OZs_SelectionChanged" Margin="-10,0,10,1" Grid.Column="0" Grid.Row="1" Height="27" VerticalAlignment="Bottom">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding OZ}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

如您所见,我试图使用DataTemplate实现数据绑定,但是它不起作用。 我知道可以用ItemsSource实现数据绑定,但是为此,我需要一个ObservableCollection,我没有它,也不知道如何从OZ创建它。 我已经看到了很多示例,其中ObservableCollection是硬编码的,并且我了解在对其进行硬编码时如何使用它,但是我不知道该怎么做。
抱歉,如果解释不清楚,我是WPF的新手。 我对这个问题很迷失。 任何帮助,将不胜感激。

编辑:根据@ Xiaoy312的答案,我添加了以下代码:

public IEnumerable<LPosition> OZList { get; set; } 

public FormelAssistent()
{
    InitializeComponent();
    this.DataContext = this;
    OZs.ItemsSource = OZList;
}

和XAML:

<ComboBox x:Name="OZs"
          SelectionChanged="OZs_SelectionChanged"
          Margin="-10,0,10,1"
          Grid.Column="0"
          Grid.Row="1"
          Height="27"
          VerticalAlignment="Bottom"
          ItemsSource="{Binding OZList}"
          DisplayMemberPath="OZ" />

但这不起作用:(

您需要提供一个内容列表(选项),以便ComboBox通过其ItemsSource属性进行选择。 您不一定需要使用ObservableCollection支持它。 仅当您计划在显示视图时添加/删除集合时。 任何IEnumerable都可以工作。

<ComboBox x:Name="OZs"
          ItemsSource="{Binding ListOrIEnumerableOfLPosition}"
          DisplayMemberPath="OZ" <- you can also use this instead of setting an item template, unless you need something complex
          ...>
    ...
</ComboBox >

如果像这样在类上实现INotifyPropertyChanged接口,它应该可以工作。

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(string PropertyName = "")
{
    if(PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
    }
}

private IEnumerable<string> _oz;
public IEnumerable<string> Oz
{
    get
    {
        return _oz;
    }
    set
    {
        _oz = value;
        NotifyPropertyChanged("Oz");
    }
}

如果碰巧正在使用依赖项对象,则可以改用依赖项属性。 如果有选择,这将是我的首选。

public IEnumerable<string> Oz
{
    get { return (IEnumerable<string>)GetValue(OzProperty); }
    set { SetValue(OzProperty, value); }
}

public static readonly DependencyProperty OzProperty = DependencyProperty.Register("Oz", typeof(IEnumerable<string>), typeof(MainWindow), new PropertyMetadata(null));  

值得指出的是,如果容器未实现INotifyCollectionChanged (例如ObservableCollection ),则当整个列表被分配替换时,您只会看到ComboBox更新。

如果您确实不能使用ObservableCollection ,则可以在get和set中进行通知。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM