【问题标题】:"SelectedValue" of comboBox in WPF has correct value but with additional text of namespaceWPF 中组合框的“SelectedValue”具有正确的值,但带有命名空间的附加文本
【发布时间】:2017-03-01 22:45:24
【问题描述】:

WPF 中组合框的“SelectedValue”具有正确的值,但带有命名空间的附加文本。我在关注 MVVM,“SelectedValue”绑定到“SelectedImage”属性。

如果我选择第一个comboBoxItem,它的值为“System.Windows.Controls.ComboBox:Firmware Image 1”。

如何只获取选定的值?

            <ComboBox Grid.Row="1"
              Grid.Column="1"
              Width="150"
              Height="30"
              ToolTip="Store Identification"
              Margin="0,2,10,0"
              HorizontalAlignment="Right"
              VerticalAlignment="Top"
              Background="#FF1649A0"
              BorderBrush="White"
              Foreground="White"

              SelectedValue="{Binding SelectedImage}">
            <ComboBox.Items>
                <ComboBoxItem Content="Firmware Image 1 " />
                <ComboBoxItem Content="Firmware Image 2" />
            </ComboBox.Items>
        </ComboBox>

【问题讨论】:

    标签: c# wpf combobox


    【解决方案1】:

    使用字符串,就可以了:

     <ComboBox Grid.Row="1"
              Width="150"
              Height="30"
              ToolTip="Store Identification"
              Margin="0,2,10,0"
              HorizontalAlignment="Right"
              VerticalAlignment="Top"
              Background="#FF1649A0"
              BorderBrush="White"
              Foreground="White"
               SelectedValue="{Binding SelectedImage}" >
            <ComboBox.Items>
                <sys:String>Firmware Image 1</sys:String>
                <sys:String>Firmware Image 2</sys:String>
            </ComboBox.Items>
        </ComboBox>
    

    添加命名空间:

      xmlns:sys="clr-namespace:System;assembly=mscorlib"
    

    【讨论】:

      【解决方案2】:

      如果您将项目绑定到ListObservableCollection,您就完成了。

      <ComboBox ItemsSource="{Binding Images}" SelectedValue="{Binding SelectedImage}" />
      

      视图模型:

      public ObservableCollection<string> Images { get; } = new ObservableCollection<string> { "Firmware Image 1", "Firmware Image 2" }; 
      public string SelectedImage { get; set; } //Maybe implemented with Notify for Two-Way Binding
      

      **编辑(第二种可能性):**

      如果您想在 xaml 中定义您的项目,您可以轻松使用:

      <ComboBox SelectedItem="{Binding SelectedImage}">
          <ComboBox.Items>
              <ComboBoxItem Content="DisplayText1" />
              <ComboBoxItem Content="DisplayText2" />
          </ComboBox.Items>
      </ComboBox>
      

      视图模型:

      //to get the text use: (SelectedImage as ComboBoxItem).Content
      public object SelectedImage { get; set; }
      

      绑定到代码隐藏中的对象,您可以执行Content 属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-15
        • 2013-02-03
        • 2013-10-26
        • 2015-09-10
        • 2013-08-31
        • 1970-01-01
        相关资源
        最近更新 更多