簡體   English   中英

WPF綁定到屬性索引?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM