【问题标题】:WPF Binding with property index?WPF与属性索引绑定?
【发布时间】:2018-06-03 03:01:48
【问题描述】:

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

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

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

【问题讨论】:

  • XAML 仅支持文字索引值。要使用参数化索引对集合进行索引,您需要编写 MultiConverter 并使用多重绑定。也就是说,如果您使用的是数组,您可能做错了什么。请在此处解释上下文;可能有更好的方法来设计整个事物。
  • which I need to bind the background of a TextBox to a value in an array 为什么需要它?

标签: c# wpf xaml binding


【解决方案1】:

所以你有两个选择。我想你要的是第一个。我在viewmodel 中设置了两个属性——一个用于颜色数组,一个用于我要使用的索引。我通过MultiConverter 向他们发送binding,以从数组中返回正确的颜色。这将允许您在运行时更新您选择的索引,并将背景更改为新选择的颜色。如果你只想要一个永远不会改变的静态索引,你应该使用实现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>

【讨论】:

    猜你喜欢
    • 2014-07-30
    • 2017-01-07
    • 2014-08-18
    • 2010-12-12
    • 2014-12-04
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多