首页 > 解决方案 > 从另一个窗口的 UserControl WPF 将 ListBoxItem 添加到窗口的 UserControl 中的 ListBox

问题描述

我有UserControl一个UserControl1包含ListBox

<UserControl x:Class="myClass.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" 
             d:DesignHeight="400" d:DesignWidth="400">
    <Grid>
        <StackPanel Width="400">
            <ListBox x:Name="lstBox_UserControl1"/>
        </StackPanel>
    </Grid>
</UserControl>

UserControl1放在我的WindowMainWindow

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:dxb="http://schemas.devexpress.com/winfx/2008/xaml/bars" x:Class="myClass.MainWindow">
        xmlns:uc="clr-namespace:myClass"
    <Grid>
        <StackPanel>
            <UserControl x:Name="usrControl_TelegramQueue" Content="{Binding CurrentView}"/>
        </StackPanel>
    </Grid>
</Window>

我有一个简单的视图模型来绑定UserControl1UserControlin MainWindow

    partial class UserControl1ViewModel : ViewModelBase {

        private object _currentView;
        UserControl1 UserControl1View= new UserControl1();

        public TelegramQueueViewModel() {
            CurrentView = UserControl1View;
        }

        public object CurrentView {
            get { return _currentView; }
            set {
                _currentView = value;
                OnPropertyChanged("CurrentView");
            }
        }
    }

该类ViewModelBase仅处理属性更改事件:

    class ViewModelBase : INotifyPropertyChanged {
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propertyName) {
            var handler = PropertyChanged;
            if (handler != null) {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

现在,我有另一个Window叫它SecondWindow,其中也有一个UserControl(称为UserControl2),类似于 how MainWindowhas UserControl1MainWindow打开SecondWindowUserControl2包含 aTextBox和 a Button。选择的按钮UserControl2被选择时,我希望在主窗口中找到ListBoxItem其文本框的内容。ListBox鉴于两个用户控件都包含在单独的窗口中,我该如何做呢?

标签: c#wpfxaml

解决方案


推荐阅读