从C#中的其他属性绑定ObservableCollections属性

时间:2016-08-17 17:16:26

标签: c# wpf data-binding observablecollection datatemplate

我拥有ObservableCollection<MobileModelInfo>类型的属性以及另外一个string类型的属性,它代表MobileModelInfo模型的名称

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

如果MobileProperty属性为“名称”,则ListBox应在MobileModelInfo

中显示ObservableCollection的名称

如果MobileProperty属性为“ Catagory ”,那么ListBox应在MobileModelInfo

中显示ObservableCollection的Catagory

型号:

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>

请帮助我...如何捆绑财产?

1 个答案:

答案 0 :(得分:0)

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