DataBind将字典值绑定到ObservableCollection C#-XAML

詹姆斯特罗德

我有一个Observable集合的自定义对象和一个公共词典变量。

我希望“ BrandName”属性充当“ Brands”词典的键,并将颜色绑定到按钮。我将如何去做呢?字典变量在类之外。

C#代码:

private ObservableCollection<BusService> BusServicesGUI;
public Dictionary<String, Brush> Brands;

public MainWindow(Dictionary<String, BusService> busServices)
{
    InitializeComponent();
    BusServicesGUI = new ObservableCollection<BusService>(BusServices.Values);
    lstMachineFunctions.ItemsSource = BusServicesGUI;
    lstMachineFunctions.Items.Refresh();
}

C#类:

public class BusService
{
    public string ServiceNumber { get; set; }
    public string BrandName { get; set; }
    public List<Location> Locations { get; set; }

    public BusService(string brandName, string serviceNumber)
    {
        BrandName = brandName;
        ServiceNumber = serviceNumber; 
        Locations = new List<Location>();
    }
}

XAML代码:

<StackPanel x:Name="ServiceStack">
    <ItemsControl x:Name="lstMachineFunctions">
        <ItemsControl.ItemTemplate  >
            <DataTemplate>   
                <Grid HorizontalAlignment="Stretch">
                    <usercontrols:BusServiceCard/>
                     <Button Tag="{Binding ServiceNumber}" Background="{Binding Brands[BrandName]}" Height="50" Click="ButtonCl"/>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</StackPanel>

从XAML中可以看到,我目前的尝试一直在尝试。Background="{Binding Brands[BrandName]}"但是这没有用,任何帮助将不胜感激。

德米特里·巴列耶夫(Dmitri Baliev)

您可以使用IValueConverter进行此操作。

public class BrandColorConverter : IValueConverter
{
    public Dictionary<String, Brush> Brands = new Dictionary<string, Brush>()
    {
        { "brand1", Brushes.Red },
        { "brand2", Brushes.Blue }
    };

    public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
    {
        if (!(value is BusService))
            return Binding.DoNothing;

        var busService = (BusService)value;

        if (!Brands.ContainsKey(busService.BrandName))
            return Binding.DoNothing;

        return Brands[busService.BrandName];
    }

    public object ConvertBack(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

在xaml中,将其添加为静态资源:

<Window.Resources>
    <local:BrandColorConverter x:Key="BrandColorConverter"/>
</Window.Resources>

并在您的按钮中使用它:

  <Button Tag="{Binding ServiceNumber}" 
     Background="{Binding Converter={StaticResource BrandColorConverter}}" 
     Height="50" 
     Click="ButtonCl"/>

此绑定转到当前元素,因此整个BusService对象将传递给转换器。

希望它能解决您的问题。

如果您打算将WPF与数据绑定一起使用,我强烈建议您研究MVVM模式,因为这会使事情更加简化。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章