使用WPF中的按钮点击更新列表框 [英] Updating a ListBox with different Content On Button Clicks in WPF

查看:187
本文介绍了使用WPF中的按钮点击更新列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的WPF应用中有一个列表框和一个工具栏。工具栏只有常规的控件,列表框有垂直扩展器。



根据点击的按钮,我需要一个不同的扩展器集。现在看起来像这样:

 < ListBox> 
< local:Select_Analysis_Panel />
< / ListBox>

其中 local:Select_Analysis_Panel 是单独的用户控制包含扩展器的文件。在按钮点击后,动态更新ListBox控件的内容的最佳方式是什么?



在过去几个小时内,我一直在尝试为每个扩展器设置并绑定到项目控件属性,使用下面的代码没有用。在设置MVVM界面之前,我只是想设计出基本框架。稍后我将替换 ItemsSource =Network_anal,你知道 ItemsSource ={Binding WhatExpanderViewModelProperty}或者类似的东西。

 < ListBox Width =250Margin =5,0,0,0> 
< ListBox.Resources>

< DataTemplate DataType =Select_Analysis_Panel>
< local:Select_Analysis_Panel />
< / DataTemplate>

< DataTemplate x:Key =Network_analDataType =NetworkAnalysis>
< local:NetworkAnalysis />
< / DataTemplate> .Resources>

< ListBox.Template>
< ControlTemplate>
< Border Background =Red/>
< / ControlTemplate>
< /ListBox.Template>

< ItemsControl ItemsSource =Network_anal/>
< / ListBox>

我正在采取正确的方法吗?



这是我要做的事情。下面点击文件按钮时,侧栏显示这两个扩展器:



解决方案

选项1:



对这些部分进行子类化:



可以使用基础部分类和特定的 DataTemplate

 < Window x:Class =MiscSamples.MultiToolbar
xmlns =http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x =http:/ /schemas.microsoft.com/winfx/2006/xaml
xmlns:local =clr-namespace:MiscSamples
Title =MultiToolbarHeight =300Width =300>
< Window.Resources>
< BooleanToVisibilityConverter x:Key =BoolToVisibilityConverter/>
< /Window.Resources>
& DockPanel>
< ListBox ItemsSource ={Binding Sections}
SelectedItem ={Binding SelectedSection}
DisplayMemberPath =Name
DockPanel.Dock =Top>
< ListBox.ItemContainerStyle>
< Style TargetType =ListBoxItem>
< Setter Property =IsEnabledValue ={Binding IsEnabled}/>
< Setter Property =VisibilityValue ={Binding IsVisible,Converter = {StaticResource BoolToVisibilityConverter}}/>
< Setter属性=MinWidth值=80/>
< Setter Property =MinHeightValue =40/>
< Setter Property =Template>
< Setter.Value>
< ControlTemplate TargetType =ListBoxItem>
< Border BorderBrush =BlackBorderThickness =1>
< ToggleButton IsChecked ={Binding IsSelected,Mode = TwoWay,RelativeSource = {RelativeSource TemplatedParent}}>
< ContentPresenter ContentSource =Content/>
< / ToggleButton>
< / Border>
< / ControlTemplate>
< /Setter.Value>
< / Setter>
< / Style>
< /ListBox.ItemContainerStyle>
< ListBox.ItemsPanel>
< ItemsPanelTemplate>
< StackPanel Orientation =Horizo​​ntal/>
< / ItemsPanelTemplate>
< /ListBox.ItemsPanel>
< / ListBox>

< ScrollViewer Width =300DockPanel.Dock =Left>
< ContentPresenter Content ={Binding SelectedSection}>
< ContentPresenter.Resources>
< DataTemplate DataType ={x:Type local:FileSection}>
< TextBlock Text =文件部分的用户控件/>
< / DataTemplate>
< DataTemplate DataType ={x:Type local:NetworkDesignSection}>
< TextBlock Text =网络设计的用户控制/>
< / DataTemplate>
< DataTemplate DataType ={x:Type local:SelectAnalysisSection}>
< TextBlock Text =用于选择分析的用户控件/>
< / DataTemplate>
< /ContentPresenter.Resources>
< / ContentPresenter>
< / ScrollViewer>

< Grid Background =Gray>
< TextBlock Text =Design SurfaceTextAlignment =CenterVerticalAlignment =CenterFontWeight =Bold/>
< / Grid>
< / DockPanel>
< / Window>

代码背后:

  public partial class MultiToolbar:Window 
{
public MultiToolbar()
{
InitializeComponent();

var vm = new MainViewModel();
vm.Sections.Add(new FileSection(){Name =File});
vm.Sections.Add(new NetworkDesignSection(){Name =Network Design});
vm.Sections.Add(new SelectAnalysisSection(){Name =Select Analysis});

DataContext = vm;
}
}

主ViewModel:

  public class MainViewModel:PropertyChangedBase 
{
private ObservableCollection< Section> _sections;
public ObservableCollection< Section>节
{
get {return _sections? (_sections = new ObservableCollection< Section>()); }
}

private Section _selectedSection;
public Section SelectedSection
{
get {return _selectedSection; }
set
{
_selectedSection = value;
OnPropertyChanged(SelectedSection);
}
}
}

部分:

  public abstract class Section:PropertyChangedBase 
{
public string Name {get;组; }

private bool _isEnabled = true;
public bool IsEnabled
{
get {return _isEnabled; }
set
{
_isEnabled = value;
OnPropertyChanged(IsEnabled);
}
}

private bool _isVisible = true;
public bool IsVisible
{
get {return _isVisible; }
set
{
_isVisible = value;
OnPropertyChanged(IsVisible);
}
}

//可选
// public string ImageSource {get; set;}
// ImageSource =/ Resources / MySection。 png
}

public class FileSection:Section
{
/// ...本节特定的自定义逻辑
}

public class NetworkDesignSection:Section
{
/// ...本节特定的自定义逻辑
}

public class SelectAnalysisSection:section
{
/// ...特定于文件部分的自定义逻辑
}

//...etc etc etc
/ pre>

结果:





请注意,我正在使用 ToggleButton s绑定到 ListBoxItem.IsSelected 属性来模拟一个 TabControl 类行为。


So I have a listbox and a tool bar in my WPF app. The tool bar just has regular controls, and the listbox has vertical expanders.

I need the listbox to have a different set of expanders depending on what button is clicked. Right now it looks like such:

<ListBox>
    <local:Select_Analysis_Panel/>
</ListBox>

Where local:Select_Analysis_Panel is seperate user control file containing the expanders. What is the best way to go about dynamically updating the ListBox control's content upon a button click?

For the last couple hours I've been trying to use set DataTemplates for each expander set and bind the to the items control property with little avail with the code below. I'm just trying to get basic framework laid out before setting up a MVVM interface. Later on I was going to replace the ItemsSource="Network_anal" with you know ItemsSource="{Binding WhatExpanderViewModelProperty}" or something like that.

 <ListBox Width="250"  Margin="5,0,0,0">
            <ListBox.Resources>

                <DataTemplate DataType="Select_Analysis_Panel">
                    <local:Select_Analysis_Panel/>
                </DataTemplate>

                <DataTemplate x:Key="Network_anal" DataType="NetworkAnalysis">
                    <local:NetworkAnalysis/>
                </DataTemplate>.Resources>

            <ListBox.Template>                    
                <ControlTemplate>
                    <Border Background="Red"/>
                </ControlTemplate>                    
            </ListBox.Template>

            <ItemsControl ItemsSource="Network_anal"/>
</ListBox>

Am I taking the right approach to this at all?

Here's what I'm trying to do. Below when the "File" button is clicked the side bar displays these 2 expanders:

And when "Network Design" button these expanders are dipslayed:

解决方案

Option 1:

Subclassing the sections:

each of these sections could be subclassed from a base section class and a specific DataTemplate could be used for each:

<Window x:Class="MiscSamples.MultiToolbar"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MiscSamples"
        Title="MultiToolbar" Height="300" Width="300">
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
    </Window.Resources>
    <DockPanel>
        <ListBox ItemsSource="{Binding Sections}"
                 SelectedItem="{Binding SelectedSection}"
                 DisplayMemberPath="Name"
                 DockPanel.Dock="Top">
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
                    <Setter Property="Visibility" Value="{Binding IsVisible, Converter={StaticResource BoolToVisibilityConverter}}"/>
                    <Setter Property="MinWidth" Value="80"/>
                    <Setter Property="MinHeight" Value="40"/>
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="ListBoxItem">
                                <Border BorderBrush="Black" BorderThickness="1">
                                    <ToggleButton IsChecked="{Binding IsSelected, Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}">
                                        <ContentPresenter ContentSource="Content"/>
                                    </ToggleButton>
                                </Border>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>

        <ScrollViewer Width="300" DockPanel.Dock="Left">
            <ContentPresenter Content="{Binding SelectedSection}">
                <ContentPresenter.Resources>
                    <DataTemplate DataType="{x:Type local:FileSection}">
                        <TextBlock Text="User Control For File Section"/>
                    </DataTemplate>
                    <DataTemplate DataType="{x:Type local:NetworkDesignSection}">
                        <TextBlock Text="User Control For Network Design"/>
                    </DataTemplate>
                    <DataTemplate DataType="{x:Type local:SelectAnalysisSection}">
                        <TextBlock Text="User Control For Select Analysis"/>
                    </DataTemplate>
                </ContentPresenter.Resources>
            </ContentPresenter>
        </ScrollViewer>

        <Grid Background="Gray">
            <TextBlock Text="Design Surface" TextAlignment="Center" VerticalAlignment="Center" FontWeight="Bold"/>
        </Grid>
    </DockPanel>
</Window>

Code Behind:

public partial class MultiToolbar : Window
    {
        public MultiToolbar()
        {
            InitializeComponent();

            var vm = new MainViewModel();
            vm.Sections.Add(new FileSection() {Name = "File"});
            vm.Sections.Add(new NetworkDesignSection() { Name = "Network Design" });
            vm.Sections.Add(new SelectAnalysisSection() { Name = "Select Analysis" });

            DataContext = vm;
        }
    }

Main ViewModel:

public class MainViewModel: PropertyChangedBase
    {
        private ObservableCollection<Section> _sections;
        public ObservableCollection<Section> Sections
        {
            get { return _sections ?? (_sections = new ObservableCollection<Section>()); }
        }

        private Section _selectedSection;
        public Section SelectedSection
        {
            get { return _selectedSection; }
            set
            {
                _selectedSection = value;
                OnPropertyChanged("SelectedSection");
            }
        }
    }

Sections:

public abstract class Section:PropertyChangedBase
    {
        public string Name { get; set; }

        private bool _isEnabled = true;
        public bool IsEnabled
        {
            get { return _isEnabled; }
            set
            {
                _isEnabled = value;
                OnPropertyChanged("IsEnabled");
            }
        }

        private bool _isVisible = true;
        public bool IsVisible
        {
            get { return _isVisible; }
            set
            {
                _isVisible = value;
                OnPropertyChanged("IsVisible");
            }
        }

        //Optionally
        //public string ImageSource {get;set;}
        //ImageSource = "/Resources/MySection.png";
    }

    public class FileSection: Section
    {
        ///... Custom logic specific to this Section
    }

    public class NetworkDesignSection:Section
    {
        ///... Custom logic specific to this Section
    }

    public class SelectAnalysisSection: Section
    {
        ///... Custom logic specific to File Section
    }

    //...etc etc etc

Result:

Notice that I'm using ToggleButtons bound to the ListBoxItem.IsSelected property to simulate a TabControl-like behavior.

这篇关于使用WPF中的按钮点击更新列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆