0

XAMLが次のように見えるComboBoxがあります。

  <StackPanel Grid.Row = "0" Style="{DynamicResource chartStackPanel}">
        <Label    Content="Port:" HorizontalAlignment="Left" Margin="8,0,0,0"/>
        <ComboBox Width="75" Height="24" HorizontalAlignment="Right" Margin="8,0,0,0" SelectedValue="{Binding Port, Mode=OneWayToSource}">
            <ComboBoxItem Content="C43"/>
            <ComboBoxItem Content="C46" IsSelected="True"/>
            <ComboBoxItem Content="C47"/>
            <ComboBoxItem Content="C48"/>
        </ComboBox>
    </StackPanel>

上記のスタイルは次のように定義されています。

ComboBoxが最初に表示されるとき、ComboBoxに「C46」アイテムを表示したいのですが。ただし、これが読み込まれると、ComboBoxは空白になります。興味深いのは、VMのソースプロパティが「C46」に設定されていることです。誰かが私が間違っていることを言うことができますか?

4

3 に答える 3

1

ViewModel にソース コレクションがあるとのことです。では、なぜ XAML で ComboBoxItems を 1 つずつ指定するのでしょうか。ViewModel には Collection of Items プロパティと SelectedItem プロパティが必要だと思います。コンストラクターでは、SelectedItem を設定できます。次のようになります。

public ObservableCollection<MyClass> Items { get;set; }

public MyClass SelectedItem
{
  get {return this.selectedItem;}
  set {
       this.selectedItem = value;
       RaisePropertyChanged("SelectedItem");
      }
}

そして、Items プロパティが初期化された後のコンストラクターで:

this.SelectedItem = Items[x]

XAML は次のようになります。

<ComboBox Width="75" Height="24" HorizontalAlignment="Right" Margin="8,0,0,0" 
                      ItemsSource="{Binding Items}"
                      SelectedItem="{Binding Path=SelectedItem}"
                      DisplayMemberPath="Content"/>
于 2012-08-02T19:26:07.493 に答える
0

私は同じに従い、画面が読み込まれると「C46」が表示されます。ただし、バインディング値パスを指定するためにSelectedValuePathを使用しなかったため、System.Windows.Controls.ComboBoxItem: C46代わりにVM が表示されます。C46

SelectedValuePath="Content"「C46」と表示されるように使用します

于 2012-08-02T19:23:34.713 に答える
-2

// 意見

<ComboBox x:Name="cbCategories" Width="300" Height="24" ItemsSource="{Binding Categories}"
DisplayMemberPath="CategoryName" SelectedItem="{Binding SelectedCategory}" />

// ビューモデル

private CategoryModel _SelectedCategory;
        public CategoryModel SelectedCategory
        {
            get { return _SelectedCategory; }
            set
            {
                _SelectedCategory = value;
                OnPropertyChanged("SelectedCategory");
            }
        }

        private ObservableCollection<CategoryModel> _Categories;
        public ObservableCollection<CategoryModel> Categories
        {
            get { return _Categories; }
            set
            {
                _Categories = value;
                _Categories.Insert(0, new CategoryModel()
                {
                    CategoryId = 0,
                    CategoryName = " -- Select Category -- "
                });
                SelectedCategory = _Categories[0];
                OnPropertyChanged("Categories");

            }
        }
于 2015-10-29T18:55:18.023 に答える