WPF ComboBox 下拉框绑定 Binding

WPF ComboBox 下拉框绑定 Binding

XAML:

<Window.DataContext>
    <local:VMTempTest/>
</Window.DataContext>
<Grid>
    <StackPanel Margin="10,20,10,20" >
        <DockPanel x:Name="Combbox" Margin="0 10 0 0" >
            <StackPanel DockPanel.Dock="Left">
                <ComboBox Width="200"  HorizontalAlignment="Left" ItemsSource="{Binding CombboxList}" 
                          SelectedItem="{Binding CombboxItem}" DisplayMemberPath="Text" SelectedValuePath="Key" ></ComboBox>
            </StackPanel>

            <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" VerticalAlignment="Center" Margin="20 0 0 0" DataContext="{Binding CombboxItem}" >
                <TextBlock Text="{Binding Key,StringFormat='结果:\{0\}'}" Margin="0,0,15,0" ></TextBlock>
                <TextBlock Text="{Binding Text}"></TextBlock>
            </StackPanel>

        </DockPanel>
    </StackPanel>
</Grid>

Model:

public class ComplexInfoModel : ObservableObject
{
    private String key;
    /// <summary>
    /// Key值
    /// </summary>
    public String Key
    {
        get { return key; }
        set { key = value; RaisePropertyChanged(() => Key); }
    }

    private String text;
    /// <summary>
    /// Text值
    /// </summary>
    public String Text
    {
        get { return text; }
        set { text = value; RaisePropertyChanged(() => Text); }
    }
}

ViewModel:

public class VMTempTest : ViewModelBase
{
    public VMTempTest()
    {
        CombboxList = new ObservableCollection<ComplexInfoModel>() {
          new ComplexInfoModel(){ Key="1",Text="苹果" },
          new ComplexInfoModel(){ Key="2",Text="香蕉" },
          new ComplexInfoModel(){ Key="3",Text="梨" },
          new ComplexInfoModel(){ Key="4",Text="樱桃" },
        };

        combboxItem = CombboxList[0];  // 默认选中第一个
    }


    private ComplexInfoModel combboxItem;
    /// <summary>
    /// 下拉框选中信息
    /// </summary>
    public ComplexInfoModel CombboxItem
    {
        get { return combboxItem; }
        set { combboxItem = value; RaisePropertyChanged(() => CombboxItem); }
    }

    private ObservableCollection<ComplexInfoModel> combboxList;
    /// <summary>
    /// 下拉框列表
    /// </summary>
    public ObservableCollection<ComplexInfoModel> CombboxList
    {
        get { return combboxList; }
        set { combboxList = value; RaisePropertyChanged(() => CombboxList); }
    }
}



参考:

https://www.cnblogs.com/wzh2010/p/6425060.html

上一篇:C#的Winform程序中设置下拉框ComboBox控件默认选中某一项【转载】


下一篇:第19天 | 28天学会PyQt5,列表选择,你选西施还是杨玉环?