WPF绑定属性索引?

时间:2018-06-03 03:01:48

标签: c# wpf xaml binding

我有一个项目,我需要将TextBox的背景绑定到数组中的值,其中索引是DataContext中的属性:

Binding backgroundBinding= new Binding();
backgroundBinding.Path = new PropertyPath($"Elements[{Index}].Value");

我一直在代码隐藏中创建绑定,但希望找到一种更好,更优雅的方法来实现它。我是否必须创建自定义转换器,或者是否有某种方法可以引用XAML中的Index属性?

1 个答案:

答案 0 :(得分:0)

所以你在这里有两个选择。我想你要求第一个。我在viewmodel中设置了两个属性 - 一个用于颜色数组,然后一个用于我想要使用的索引。我通过binding MultiConverter向他们发送,以便从数组中返回正确的颜色。这将允许您在运行时更新所选索引,并将背景更改为新选择的颜色。如果您只想要一个永不改变的静态索引,则应使用实现IValueConverter而不是IMultiValueConverter,然后使用ConverterParameter属性传递索引。

作为旁注,我选择将数组实现为Color类型。 SolidColorBrush对象价格昂贵,这样做有助于降低成本。

public class ViewModel : INotifyPropertyChanged
{
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private Color[] _backgroundColours = new Color[] { Colors.AliceBlue, Colors.Aqua, Colors.Azure };
    public Color[] BackgroundColours
    {
        get => _backgroundColours;
        set
        {
            _backgroundColours = value;
            OnPropertyChanged();
        }
    }

    private int _backgroundIndex = 1;

    public int ChosenIndex
    {
        get => _backgroundIndex;
        set
        {
            _backgroundIndex = value;
            OnPropertyChanged();
        }
    }
}

...

public class BackgroundConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var backgroundColours = values[0] as Color[];
        var chosenIndex = (int)values[1];

        return new SolidColorBrush(backgroundColours[chosenIndex]);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

...

<Grid>
    <Grid.DataContext>
        <local:ViewModel />
    </Grid.DataContext>
    <Grid.Resources>
        <local:BackgroundConverter x:Key="backgroundConverter"/>
    </Grid.Resources>
    <TextBox>
        <TextBox.Background>
            <MultiBinding Converter="{StaticResource backgroundConverter}">
                <Binding Path="BackgroundColours" />
                <Binding Path="ChosenIndex" />
            </MultiBinding>
        </TextBox.Background>
    </TextBox>
</Grid>