我有一个项目,需要将 TextBox 的背景绑定(bind)到数组中的值,其中索引是 DataContext 中的属性:
Binding backgroundBinding= new Binding();
backgroundBinding.Path = new PropertyPath($"Elements[{Index}].Value");
我一直在代码隐藏中创建绑定(bind),但想找到一种更好、更优雅的方法来完成它。我是否必须创建一个自定义转换器,或者是否有某种方法可以在 XAML 中引用 Index 属性?
最佳答案
所以你有两个选择。我想你问的是第一个。我在我的 viewmodel
中设置了两个属性 - 一个用于颜色数组,另一个用于我要使用的索引。我通过 MultiConverter 绑定(bind)到它们,以从数组中返回正确的颜色。这将允许您在运行时更新所选索引,并将背景更改为新选择的颜色。如果您只想要一个永不更改的静态索引,则应该使用实现 IValueConverter
而不是 IMultiValueConverter
,然后使用 ConverterParameter
传递索引> 属性(property)。
附带说明一下,我选择将数组实现为 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>
关于c# - WPF 与属性索引绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50662926/