WPF MVVM中组合框的默认值

时间:2014-03-17 22:25:00

标签: c# wpf mvvm combobox

我正在使用以下代码在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;
         }
}               

2 个答案:

答案 0 :(得分:0)

SelectedItem是通过绑定设置的。确保视图模型上的SetWidth默认设置为3,并且应该没问题

答案 1 :(得分:0)

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

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

让我知道它是否有帮助。 谢谢, 库马尔