WPF:基于ListView选择将控件添加到网格的最简单方法

时间:2013-12-17 11:20:39

标签: c# wpf xaml listview

我有一个ListView,其中包含应代表某些设置的项目,这些设置可由用户更改。我正在寻找将ListViewItem链接到自定义用户控件的最简单方法。

我现在拥有的:

    <ListView 
        Grid.Row="0" 
        Grid.Column="0"
        SelectionChanged="SettingsListViewSelectionChanged">

        <ListViewItem x:Name="PathSettings" Content="Path"/>
        <ListViewItem x:Name="HideShowTvShows" Content="Hide/Show TV Shows"/>
    </ListView>

然后在后面的代码中我找出点击了哪个项目,并将相应的UserControl附加到Grid

    private void SettingsListViewSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var listView = e.Source as ListView;

        if (listView != null)
        {
            SettingsContentPanel.Children.Clear();

            if (listView.SelectedItem.Equals(_pathSettings))
            {
                SettingsContentPanel.Children.Add(_pathSettings);

                _pathSettings.SetValue(Grid.RowProperty, 0);
                _pathSettings.SetValue(Grid.ColumnProperty, 1);
            }
            if (listView.SelectedItem.Equals(_hideShowTvShowsSettings))
            {
                SettingsContentPanel.Children.Add(_hideShowTvShowsSettings);

                _hideShowTvShowsSettings.SetValue(Grid.RowProperty, 0);
                _hideShowTvShowsSettings.SetValue(Grid.ColumnProperty, 1);
            }
        }
    }

网格本身:

    <Grid 
        x:Name="SettingsContentPanel" 
        Grid.Row="0" 
        Grid.Column="2" 
        Grid.ColumnSpan="2" />

有没有办法摆脱背后的锅炉板代码并为此目的使用XAML?

1 个答案:

答案 0 :(得分:1)

看起来您正在寻找ContentPresenter

<ContentPresenter x:Name="SettingsContentPanel"
                  Content="{Binding SelectedItem, ElementName=MyLstView}"/>