WPF MVVM中组合框的默认值

本文关键字:默认值 组合 MVVM WPF | 更新日期: 2023-09-27 17:50:51

我使用下面的代码在ComboBox中显示num,

但是没有显示默认的文本3。请帮忙.....

请帮忙.....

等待你的回答。

<StackPanel  Orientation="Horizontal" Grid.Row="1">
<TextBlock Text="Width " VerticalAlignment="Center" Width="42" Margin="2,0,0,0"/>
<ribbon:ComboBox VerticalAlignment="Center" Text="3"  SelectedItem="{Binding SetWidth}"    Width="50" MinHeight="20" Margin="0,1,0,0">
    <ComboBoxItem Tag="1" Content="1" />
    <ComboBoxItem Tag="2" Content="2"/>
    <ComboBoxItem Tag="3" IsSelected="True" Content="3"/>
    <ComboBoxItem Tag="4" Content="4"/>
</ribbon:ComboBox>
</StackPanel>    
背后代码:

private ComboBoxItem _setWidth = new ComboBoxItem();
public ComboBoxItem SetPointWidth   
{ 
  get
    {
      _setWidth.Content = Chart.Width;
      _setWidth.IsSelected = true;
       return _setWidth;
    }
        set
        {
            if ((value == null) || (_setPointWidth == value))
                return;
            _setPointWidth = value;
         }
}               

WPF MVVM中组合框的默认值

如果我的理解是正确的,下面将解决您的问题

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ComboBox VerticalAlignment="Center" Text="3"  SelectedItem="{Binding SetWidth}" MinHeight="20">
            <sys:String >1</sys:String>
            <sys:String >2</sys:String>
            <sys:String >3</sys:String>
            <sys:String >4</sys:String>
            </ComboBox>
    </Grid>
</Window>

 public partial class MainWindow : Window 
    {
        private string _setWidth;
        public string SetWidth
        {
            get
            {
                return _setWidth;
            }
            set
            {
                if ((value == null) || (_setWidth == value))
                    return;
                _setWidth = value;
                RaisePropertyChanged("SetWidth");
            }
        }       
        public MainWindow()
        {

            InitializeComponent();
            SetWidth = "3";
            this.DataContext = this;
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void RaisePropertyChanged(string name)
        {
            if (PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

如果有帮助,请告诉我。谢谢,Kumar

SelectedItem是通过绑定设置的。确保视图模型的SetWidth默认设置为3,它应该是OK