簡體   English   中英

使用資源和轉換器將 UWP 綁定到 ComboBoxItem

[英]UWP Binding to ComboBoxItem using resources and converter

我有這樣的組合框:

<ComboBox Grid.Column="1" Padding="0" Margin="5,0,0,0" VerticalAlignment="Center" HorizontalContentAlignment="Center" IsEnabled="{Binding CanUserEdit}" SelectedValue="{Binding ConfigValue, Converter={StaticResource BoolToStringConverter}, Mode=TwoWay}">
      <ComboBoxItem x:Uid="NoButton" />
      <ComboBoxItem x:Uid="YesButton" />
</ComboBox>

它應該是正常的 Yes/No 類型的 ComboBox,但我想避免綁定到某些 Yes/No ItemsSource 以避免不必要的並發症。

BoolToStringConverter 看起來像這樣:

public class BoolToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var val = value as bool?;

        if (val == true)
            return ResourceLoader.GetForCurrentView().GetString("YesButton/Content");
        else
            return ResourceLoader.GetForCurrentView().GetString("NoButton/Content");
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        var val = value as string;

        if (val == ResourceLoader.GetForCurrentView().GetString("YesButton/Content"))
            return new bool?(true);
        else
            return new bool?(false);
    }
}

所以一般來說,我有來自 ComboBoxItem 內部資源的字符串,而 ViewModel 內部的值是一個對象(它不是 bool,它不像我使用 TemplateSelector 那樣簡單,ComboBox 應該僅用於布爾值,其他人將是普通的 TextBox里面的字符串)。

我從 ViewModel 中獲取值,將其從資源中轉換為完全相同的字符串,但是在加載控件時它沒有映射 SelectedValue(ComboBox 為空,即使它應該包含 Yes/No 值)。 但“ConvertBack”工作正常。 當我在這個 ComboBox 中選擇一些東西(例如“No”值)時,它會正確地進入 ConvertBack 方法,比較字符串並設置正確的布爾值? ViewModel 中的值。 因此 ConvertBack 運行良好,但初始 Convert 沒有正確設置 SelectedValue,因為此時它似乎無法將“Yes”識別為“Yes”,“No”識別為“No”(可能是因為它試圖比較字符串和組合框項)。 我該如何解決?

當我使用 x:String 而不是 ComboBoxItem 時,它可以工作……但是 x:String 無法本地化,而且我不想針對某些語言對其進行硬編碼。

問題是類型不匹配。

在您的 XAML 中, ComboBox的子項類型是ComboBoxItem ,並且您的BoolToStringConverter.Convert方法返回一個string 這兩種類型不能建立正確的等價關系。

您可以嘗試在ComboBox設置SelectedValuePath屬性:

<ComboBox Grid.Column="1" 
          ...
          SelectedValuePath="Content">
    <ComboBoxItem x:Uid="NoButton" />
    <ComboBoxItem x:Uid="YesButton" />
</ComboBox>

但我推薦使用ItemsSource進行數據源綁定,並使用DataTemplate設置子項的布局。

這是一個關於綁定的例子,你可以在ComboBox上做同樣的事情

此致。

暫無
暫無

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

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