[英]WPF Binding with property index?
我有一个项目,需要将TextBox的背景绑定到数组中的值,其中索引是DataContext中的属性:
Binding backgroundBinding= new Binding();
backgroundBinding.Path = new PropertyPath($"Elements[{Index}].Value");
我一直在后面的代码中创建绑定,但是想要找到一种更好,更优雅的方法来进行绑定。 我必须创建一个自定义转换器,还是可以通过某种方式在XAML中引用Index属性?
因此,您在这里有两个选择。 我想您正在要求第一个。 我在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.