首页 > Windows开发 > 详细

WPF ComboBox 下拉框绑定 Binding

时间:2021-08-12 23:45:10      阅读:82      评论:0      收藏:0      [点我收藏+]

技术分享图片

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); }
    }
}



WPF ComboBox 下拉框绑定 Binding

原文:https://www.cnblogs.com/huvjie/p/15135064.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!