如何隐藏和基于的SelectedItem的ListBox中的WPF MVVM模式显示用户控件 [英] How to hide and show UserControls based on SelectedItem in ListBox WPF MVVM Model

查看:962
本文介绍了如何隐藏和基于的SelectedItem的ListBox中的WPF MVVM模式显示用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的主窗口3用户控件,在我的UserControl1我有一些names.The UserControl2一个列表框和3是不可见的,当我们启动应用程序。

在我的UserControl1列表框中选择一些名字,那么usercontrol2应该出现在我的主窗口,当我选择其他名称,然后usercontrol3应该出现在我的mainwindow.Struggling与此请帮助我,我是新来这个

这是我的UserControlXaml code

 <用户控件X:类=Wpf_MVVM.UserControl1
         的xmlns =htt​​p://schemas.microsoft.com/winfx/2006/xaml/$p$psentation
         的xmlns:X =htt​​p://schemas.microsoft.com/winfx/2006/xaml
         的xmlns:MC =htt​​p://schemas.openxmlformats.org/markup-compatibility/2006
         的xmlns:D =htt​​p://schemas.microsoft.com/ex$p$pssion/blend/2008
         MC:可忽略=D
         X:NAME =UC1HEIGHT =自动WIDTH =自动>
<网格和GT;
    <列表框名称=列表框的ItemsSource ={结合MYLIST}的Horizo​​ntalAlignment =左HEIGHT =310VerticalAlignment =评出的WIDTH =150保证金=0,40,0,0字号= 15>    < /列表框>
    <标签内容=对话的Horizo​​ntalAlignment =左VerticalAlignment =评出的HEIGHT =40WIDTH =150字号=20背景=天蓝/>
    <按钮内容=创建新的聊天室HEIGHT =30的Horizo​​ntalAlignment =左保证金=0,350,0,0VerticalAlignment =评出的WIDTH =150/>< /网格和GT;
< /用户控件>

这是我的.cs code

 公共部分类的UserControl1:用户控件
{
    用户1用户1 =新用户1();
    公众的UserControl1()
    {
        的InitializeComponent();
        this.DataContext =用户1;
    }
}
公共类用户1
{
    私人的ObservableCollection<串GT; _mylist =新的ObservableCollection<串GT;();    公众的ObservableCollection<串GT; MYLIST {{返回_mylist; }}    公众用户1()
    {
        mylist.Add(名称1);
        mylist.Add(名称2);
        mylist.Add(NAME3);
        mylist.Add(NAME4);    }

这是我的mainwindow.xaml code

 <窗​​口x:类=Wpf_MVVM.MainWindow
    的xmlns =htt​​p://schemas.microsoft.com/winfx/2006/xaml/$p$psentation
    的xmlns:X =htt​​p://schemas.microsoft.com/winfx/2006/xaml
    XMLNS:地方=CLR的命名空间:Wpf_MVVM
    标题=主窗口背景=青灰HEIGHT =420WIDTH =550>
< Window.Resources>
    < BooleanToVisibilityConverter X:键=VisibilityConverter/>
< /Window.Resources><网格和GT;    <局部:的UserControl1 X:NAME =UC1的Horizo​​ntalAlignment =左VerticalAlignment =顶部/>
    <&StackPanel的GT;        <局部:UserControl2 X:NAME =UC2能见度={结合的SelectedItem,转换器= {StaticResource的VisibilityConverter}}的Horizo​​ntalAlignment =左VerticalAlignment =评出的保证金=150,29,0,0/&GT ;
        <局部:UserControl3 X:NAME =UC3能见度={结合SelectedItem1,转换器= {StaticResource的VisibilityConverter}}的Horizo​​ntalAlignment =左VerticalAlignment =评出的保证金=340,29,0,0/&GT ;
    < / StackPanel的>< /网格和GT;
< /窗GT;

这是我的视图模型code为usercontrol2和3

 公共类用户:INotifyPropertyChanged的
    {        私人布尔_selectedItem;
        公共BOOL的SelectedItem
        {
            {返回_selectedItem; }
            组
            {
                _selectedItem =价值;
                的PropertyChanged(这一点,新PropertyChangedEventArgs(的SelectedItem));
            }
        }
        私人布尔_selectedItem1;
        公共BOOL SelectedItem1
        {
            {返回_selectedItem1; }
            组
            {
                _selectedItem1 =价值;
                的PropertyChanged(这一点,新PropertyChangedEventArgs(SelectedItem1));
            }
        }        公共类BooleanToVisibilityConverter:的IValueConverter
        {
            公共对象转换(对象的值,类型TARGETTYPE,对象参数,CultureInfo的文化)
            {                返回值== NULL? Visibility.Collapsed:Visibility.Visible;
            }            公共对象ConvertBack(对象的值,类型TARGETTYPE,对象参数,CultureInfo的文化)
            {                返回null;
            }        }
        公共事件PropertyChangedEventHandler的PropertyChanged;
        私人无效通知(字符串propertyName的)
        {
            VAR处理器=的PropertyChanged;
            如果(处理!= NULL)
                处理器(这一点,新PropertyChangedEventArgs(propertyName的));
        }        私人只读的ObservableCollection<串GT;项目=新的ObservableCollection<串GT;();
        私人字符串文本;
        私人只读的ObservableCollection<串GT; newitems =新的ObservableCollection<串GT;();
        私人字符串newtext;        公共类命令:ICommand的
        {
            私人只读操作动作;            公共命令(动作动作)
            {
                this.action =行动;
            }            公共BOOL CanExecute(对象参数)
            {
                返回true;
            }
            公共事件的EventHandler CanExecuteChanged;
            公共无效执行(对象参数)
            {
                行动();
            }
        }        私人只读的ICommand addCommand;
        私人只读的ICommand sendCommand;
        公共用户()
        {            addCommand =新司令部(()=> items.Add(文本));
            sendCommand =新司令部(()=> newitems.Add(NewText));
        }        公共IEnumerable的<串GT;项目
        {
            {返回的物品; }
        }        公共IEnumerable的<串GT;新东西
        {
            {返回newitems; }
        }
        公众的ICommand AddCommand
        {
            {返回addCommand; }
        }
        公众的ICommand SendCommand
        {
            {返回sendCommand; }
        }        公共字符串文本
        {
            {返回文本; }
            组
            {
                如果(文字==值)
                    返回;                文本=价值;
                通知(文本);
            }
        }
        公共字符串NewText
        {
            {返回newtext; }
            组
            {
                如果(newtext ==值)
                    返回;                newtext =价值;
                通知(NewText);
            }
        }
    }
}


解决方案

如果您想使用 BooleanToVisibilityConverter ,那么你需要创建一些布尔在你看来模特属性:

 公共BOOL IsControl1Visible
{
    {返回isControl1Visible; }
    集合{isControl1Visible =价值; NotifyPropertyChanged(IsControl1Visible); }
}公共BOOL IsControl2Visible
{
    {返回isControl2Visible; }
    集合{isControl2Visible =价值; NotifyPropertyChanged(IsControl2Visible); }
}

然后,你需要一个的SelectedItem 属性:

 公共字符串的SelectedItem
{
    {返回selectedItem属性; }
    集合{将selectedItem =价值; NotifyPropertyChanged(的SelectedItem); }
}

您还需要创建一个的SelectedItem的DependencyProperty 在你的第一个用户控件并绑定该到 ListBox.SelectedItem 属性(我假设你要么懂得,也可以了解如何创建一个的DependencyProperty ):

的UserControl1

 <列表框名称=列表框的ItemsSource ={结合MYLIST}
    的SelectedItem ={结合的SelectedItem,的RelativeSource = {AncestorType = {X:类型
    本地:的UserControl1}}}的Horizo​​ntalAlignment =左HEIGHT =310
    VerticalAlignment =评出的WIDTH =150保证金=0,40,0,0字号=15/>

然后你可以绑定 UserControl1.SelectedItem 属性(内部绑定到 ListBox.SelectedItem 属性)到您的视图模型:

 <局部:的UserControl1 X:NAME =UC1的SelectedItem ={结合的SelectedItem}
    的Horizo​​ntalAlignment =左VerticalAlignment =顶部/>

最后,我们可以更新我们的视图模型的SelectedItem 属性来更改其他用户控件 S上的可见度:

 公共字符串的SelectedItem
{
    {返回selectedItem属性; }
    组
    {
        将selectedItem =价值;
        NotifyPropertyChanged(的SelectedItem);
        如果(将selectedItem ==一些价值)
        {
            IsControl1Visible = TRUE;
            IsControl2Visible = FALSE;
        }
        其他
        {
            IsControl2Visible = TRUE;
            IsControl1Visible = FALSE;
        }
    }
}

作为替代这种方法,您的可能的找到我的答案的 WPF MVVM导航意见发布有用的。

I have 3 UserControls in my MainWindow,In my UserControl1 i have a ListBox with some names.The UserControl2 and 3 are not visible when we start the application.

When i select some name in the listbox of usercontrol1 then the usercontrol2 should appear on my mainwindow,when i select other name then usercontrol3 should appear on my mainwindow.Struggling with this please help me,i'm new to this

This is my UserControlXaml code

<UserControl x:Class="Wpf_MVVM.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         x:Name="uc1" Height="Auto" Width="Auto">
<Grid>
    <ListBox Name="listbox" ItemsSource="{Binding mylist}"  HorizontalAlignment="Left" Height="310" VerticalAlignment="Top" Width="150" Margin="0,40,0,0" FontSize="15">

    </ListBox>
    <Label Content="Conversations" HorizontalAlignment="Left" VerticalAlignment="Top"  Height="40" Width="150" FontSize="20" Background="SkyBlue"/>
    <Button Content="Create New Chat" Height="30" HorizontalAlignment="Left" Margin="0,350,0,0" VerticalAlignment="Top" Width="150"/>

</Grid>
</UserControl>

This is my .cs code

public partial class UserControl1 : UserControl
{
    User1 User1 = new User1();
    public UserControl1()
    {
        InitializeComponent();
        this.DataContext = User1;
    }
}
public class User1
{
    private ObservableCollection<string> _mylist = new ObservableCollection<string>();

    public ObservableCollection<string> mylist { get { return _mylist; } }

    public User1()
    {
        mylist.Add("Name1");
        mylist.Add("Name2");
        mylist.Add("Name3");
        mylist.Add("Name4");

    }

This is my mainwindow.xaml code

<Window x:Class="Wpf_MVVM.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Wpf_MVVM" 
    Title="MainWindow" Background="SlateGray" Height="420" Width="550" >
<Window.Resources>
    <BooleanToVisibilityConverter x:Key="VisibilityConverter" />
</Window.Resources>

<Grid>

    <local:UserControl1 x:Name="uc1"   HorizontalAlignment="Left" VerticalAlignment="Top"/>
    <StackPanel>

        <local:UserControl2 x:Name="uc2"  Visibility="{Binding SelectedItem, Converter={StaticResource VisibilityConverter}}"  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="150,29,0,0" />
        <local:UserControl3 x:Name="uc3" Visibility="{Binding SelectedItem1, Converter={StaticResource VisibilityConverter}}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="340,29,0,0"/>


    </StackPanel>



</Grid>
</Window>

This is my viewmodel code for usercontrol2 and 3

  public class User : INotifyPropertyChanged
    {

        private bool _selectedItem;
        public bool SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                _selectedItem = value;
                PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem"));
            }
        }
        private bool _selectedItem1;
        public bool SelectedItem1
        {
            get { return _selectedItem1; }
            set
            {
                _selectedItem1 = value;
                PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem1"));
            }
        }

        public class BooleanToVisibilityConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {

                return value == null ? Visibility.Collapsed : Visibility.Visible;
            }

            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {

                return null;
            }

        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void Notify(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }

        private readonly ObservableCollection<string> items = new ObservableCollection<string>();
        private string text;
        private readonly ObservableCollection<string> newitems = new ObservableCollection<string>();
        private string newtext;

        public class Command : ICommand
        {
            private readonly Action action;

            public Command(Action action)
            {
                this.action = action;
            }

            public bool CanExecute(object parameter)
            {
                return true;
            }


            public event EventHandler CanExecuteChanged;
            public void Execute(object parameter)
            {
                action();
            }
        }

        private readonly ICommand addCommand;
        private readonly ICommand sendCommand;
        public User()
        {

            addCommand = new Command(() => items.Add(Text));
            sendCommand = new Command(() => newitems.Add(NewText));
        }



        public IEnumerable<string> Items
        {
            get { return items; }
        }

        public IEnumerable<string> NewItems
        {
            get { return newitems; }
        }


        public ICommand AddCommand
        {
            get { return addCommand; }
        }
        public ICommand SendCommand
        {
            get { return sendCommand; }
        }

        public string Text
        {
            get { return text; }
            set
            {
                if (text == value)
                    return;

                text = value;
                Notify("Text");
            }
        }
        public string NewText
        {
            get { return newtext; }
            set
            {
                if (newtext == value)
                    return;

                newtext = value;
                Notify("NewText");
            }
        }
    }
}

解决方案

If you want to use a BooleanToVisibilityConverter, then you'll need to create some bool properties in your view model:

public bool IsControl1Visible
{
    get { return isControl1Visible; }
    set { isControl1Visible = value; NotifyPropertyChanged("IsControl1Visible"); }
}

public bool IsControl2Visible
{
    get { return isControl2Visible; }
    set { isControl2Visible = value; NotifyPropertyChanged("IsControl2Visible"); }
}

Then you'll need a SelectedItem property:

public string SelectedItem
{
    get { return selectedItem; }
    set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}

You'll also need to create a SelectedItem DependencyProperty in your first UserControl and bind that to the ListBox.SelectedItem property (I'm assuming that you either know how to or can find out how to create a DependencyProperty):

In UserControl1:

<ListBox Name="listbox" ItemsSource="{Binding mylist}" 
    SelectedItem="{Binding SelectedItem, RelativeSource={AncestorType={x:Type 
    local:UserControl1}}}" HorizontalAlignment="Left" Height="310" 
    VerticalAlignment="Top" Width="150" Margin="0,40,0,0" FontSize="15" />

Then you can Bind the UserControl1.SelectedItem property (which is internally bound to the ListBox.SelectedItem property) to your view model:

<local:UserControl1 x:Name="uc1" SelectedItem="{Binding SelectedItem}" 
    HorizontalAlignment="Left" VerticalAlignment="Top"/>

Finally, we can update our view model SelectedItem property to change the visibility of the other Usercontrols:

public string SelectedItem
{
    get { return selectedItem; }
    set 
    {
        selectedItem = value;
        NotifyPropertyChanged("SelectedItem");
        if (selectedItem == "Some value") 
        {
            IsControl1Visible = true;
            IsControl2Visible = false;
        }
        else
        {
            IsControl2Visible = true;
            IsControl1Visible = false;
        }
    }
}

As an alternative to this method, you may find my answer to the WPF MVVM navigate views post useful.

这篇关于如何隐藏和基于的SelectedItem的ListBox中的WPF MVVM模式显示用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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