【问题标题】:Bind ObservableCollections Property from other Property in C#从 C# 中的其他属性绑定 ObservableCollections 属性
【发布时间】:2016-08-17 17:16:26
【问题描述】:

我有一个ObservableCollection<MobileModelInfo> 类型的属性和一个string 类型的属性,它代表MobileModelInfo 模型的名称

我需要使用MobileProperty 属性绑定DataTemplate 中的属性以循环MobileList 属性。

如果MobileProperty 属性为“Name”,则ListBox 应在ObservableCollection 中显示MobileModelInfo 的名称

如果MobileProperty 属性为“类别”,则ListBox 应在ObservableCollection 中显示MobileModelInfo 类别

型号:

public class MobileModelInfo
{
    public string Name { get; set; }
    public string Catagory { get; set; }
    public string Year { get; set; }
}

查看模型:

public class MobileViewModel{
    private ObservableCollection<MobileModelInfo> _mobileList;
    public ObservableCollection<MobileModelInfo> MobileList
    {
        get { return _mobileList; }
        set { _mobileList = value; OnPropertyChanged(); }
    }

    private string _mobileProperty;
    public string MobileProperty
    {
        get { return _mobileProperty; }
        set { _mobileProperty= value; OnPropertyChanged(); }
    }

    public MobileViewModel()
    {
        MobileList = ObservableCollection<MobileModelInfo>();
        MobileList.Add(new MobileModelInfo { Name = "iPhone 4", Catagory = "Smart Phone", Year = "2011" });
        MobileList.Add(new MobileModelInfo { Name = "iPhone 5", Catagory = "Smart Phone", Year = "2013" });
        MobileList.Add(new MobileModelInfo { Name = "iPhone 6", Catagory = "Premium Smart Phone", Year = "2015" });

        MobileProperty = "Name"; 
    }
}

XAML:

<ListBox ItemsSource="{TemplateBinding MobileList}" x:Name="iListBox" BorderBrush="Transparent" BorderThickness="0"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding }" />
            </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

请帮助我...如何绑定属性?

【问题讨论】:

    标签: c# wpf data-binding observablecollection datatemplate


    【解决方案1】:

    我使用https://github.com/Fody/PropertyChanged 对于绑定我使用的任何模型 [ImplementPropertyChanged] 和所有

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 2021-08-31
      相关资源
      最近更新 更多