应在WPF中的应用程序启动时默认选择ListView项目

时间:2012-10-09 12:21:43

标签: c# wpf xaml listview textbox

我的xaml文件中有一个listview和一个文本框。

查看:

<ListView Grid.Column="0" ItemsSource="{Binding I2CDeviceList}" SelectedItem="{Binding SelectedI2CDeviceList, Mode=TwoWay}" Name="I2cDeviceList" >
       <ListView.View>
              <GridView>
                    <GridViewColumn Header="I2C Device" Width="Auto" DisplayMemberBinding="{Binding I2CDevName}" />
                    <GridViewColumn Header="I2C Device Address" Width="Auto" DisplayMemberBinding="{Binding I2CDeviceAddress}" />
              </GridView>
       </ListView.View>
</ListView>

<TextBox Height="23" Grid.Column="1" Name="AddressI2C" Text="{Binding Path=AddressMessage, Mode=TwoWay}" />

查看型号:

//List View Property
public ObservableCollection<I2CModel> I2CDeviceList
    {
        get { return _I2CDeviceList; }
        set
        {
            _I2CDeviceList = value;
            NotifyPropertyChanged("I2CDeviceList");
        }
    }

    private I2CModel _selectedI2CDeviceList;
    public I2CModel SelectedI2CDeviceList
    {
        get { return _selectedI2CDeviceList; }
        set
        {
            _selectedI2CDeviceList = value;
            AddressMessage = _selectedI2CDeviceList.I2CDeviceAddress; //Displays Address in My textBox
            NotifyPropertyChanged("SelectedI2CDevSize");
        }
    }

// Property for textBox
private string _AddressMessage;
public string AddressMessage
    {
        get
        {
            return _AddressMessage;
        }
        set
        {
            _AddressMessage = value;
            NotifyPropertyChanged("AddressMessage");
        }
    }

我的要求是,

当我启动应用程序时,是否可以默认选择列表视图的第一项?即如果我的列表视图中的第一项是“芯片ID”,“0x03”,则在启动时应该默认选择,地址(0x03)也必须显示在AddressMessage文本框中。

2 个答案:

答案 0 :(得分:7)

在XAML中将SelectedIndex设置为0

答案 1 :(得分:5)

在ViewModel中将SelectedI2CDeviceList设置为启动时的默认值。我使用ViewModel构造函数来设置SelectedItem,以便在我的窗口启动时,我的视图显示所选的值。