簡體   English   中英

uwp selectedIndex綁定,枚舉不起作用

[英]uwp selectedIndex binding with enum not working twoway

所以我有一些項目的ComboBox並且它的SelectedIndexMyTypeEnum類型的屬性綁定到TwoWay上,想法是它的選定索引值可以由枚舉設置為int轉換器,並且當用戶更改組合框本身的選擇時 ,新的selectedIndex應該更新值綁定。 OneWay正常運行,即:從屬性到SelectedIndex,但不能反向運行,因此帶有斷點。我已經確認,當我更改組合框的選擇時,綁定屬性的Set方法不會執行,但是轉換器的ConvertBack方法會執行,就像這應該。

我准備了一個最小和簡單的代碼倉庫來重現此問題: https : //github.com/touseefbsb/ComboBoxToEnumBug

MainPage.xaml

<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
    <local:IdToIndexConverter x:Key="IdToIndexConverter"/>
</Page.Resources>
<Grid x:DefaultBindMode="TwoWay">
    <ComboBox SelectedIndex="{x:Bind ViewModel.MyTypeEnum, Converter={StaticResource IdToIndexConverter}}" >
        <ComboBoxItem>item 1</ComboBoxItem>
        <ComboBoxItem>item 2</ComboBoxItem>
        <ComboBoxItem>item 3</ComboBoxItem>
    </ComboBox>
</Grid>

主視圖模型

public class MainViewModel : Observable
{
    private MyTypeEnum _myTypeEnum = MyTypeEnum.Type1;

    public MyTypeEnum MyTypeEnum
    {
        get => _myTypeEnum;
        set => Set(ref _myTypeEnum, value);
    }
}

可觀察的

public class Observable : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
    {
        if (Equals(storage, value))
        {
            return;
        }

        storage = value;
        OnPropertyChanged(propertyName);
    }

    protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

MyTypeEnum

//使用字節作為父級,以便我可以從1而不是0開始計數

public enum MyTypeEnum : byte
{
    Type1 = 1,
    Type2,
    Type3
}

轉換器

public class IdToIndexConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language) => System.Convert.ToInt32(value) - 1;

    public object ConvertBack(object value, Type targetType, object parameter, string language) => ((int)value) + 1;
}

我已經確認,當我更改組合框的選擇時,綁定屬性的Set方法不會執行,但是轉換器的ConvertBack方法會執行,就像應該的那樣。

您的ConvertBack方法返回一個int但應返回一個MyTypeEnum

視圖模型的source屬性不能設置為int ,只能設置為MyTypeEnum

在C#中將int轉換為枚舉

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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