WPF ComboBox 下拉框绑定 Binding

2021/8/12 23:09:29

本文主要是介绍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



这篇关于WPF ComboBox 下拉框绑定 Binding的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程