c# - 如何从 MainWindow 中的用户控件获取数据

标签 c# wpf mvvm

我有用户控件,它有两个控件
标签 文本 block

   <UserControl x:Class=MyClass....
                 d:DesignHeight="300" d:DesignWidth="300" x:Name="MyUsrCtrl">
      <StackPanel>
           <Label Content={Binding MyLabelContent} x:Name="MyLabel"...../>
           <TextBlock Content={Binding MyTextBlockContent} x:Name="MyTextBlock"...../>
     </StackPanel>

  </UserControl> 

并且在我的 MainWindow 中,我有一个 ListBox,其 ItemSource 绑定(bind)到此用户控件的集合
 <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    <Grid>
        <ListBox x:Name="myListBox" Grid.Row="0"
             ItemsSource="{Binding Path=_myControl}"> // collection of user controls
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <local:MyUserControl x:Name="myUserControl" />
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>

如何获得 Textblock 的值和 Label在列表框中选择任何项目时?

最佳答案

这对我有用:

  • 创建了一个名为 MyControl 的模型,它“代表”了 MyUserControl
  • 中的数据
  • 创建了一个“表示”列表框中数据的 ObservableCollection
  • 这样你也可以删除所有的 x:Name
  • 从 UI 中分离数据

  • 主窗口.xaml
       <ListBox x:Name="MyListBox" Grid.Row="0"
             ItemsSource="{Binding MyControls}"
                 SelectionChanged="MyListBox_OnSelectionChanged"
                 SelectionMode="Single"
                 >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <local:MyUserControl></local:MyUserControl>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
    
        </ListBox>
    

    主窗口.cs
       public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
    
            MyControls = new ObservableCollection<MyControl>();
            var a = new MyControl { MyLabelContent = "label content 1", MyTextBlockContent = "Text content 1" };
            var b = new MyControl { MyLabelContent = "label content 2", MyTextBlockContent = "Text content 2" };
    
            MyControls.Add(a);
            MyControls.Add(b);
    
        }
    
    
        private void MyListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listBox = sender as ListBox;
            if (listBox != null)
            {
                var selectedItem = listBox.SelectedItems[0] as MyControl;
    
                var textBlockContent = selectedItem.MyTextBlockContent; //text in textblock
                var labelContent = selectedItem.MyLabelContent; //text in label
    
            }
        }
    
    
        private ObservableCollection<MyControl> _myControls;
    
    
        public ObservableCollection<MyControl> MyControls
        {
            get { return _myControls; }
            set
            {
                _myControls = value;
                NotifyPropertyChanged("MyControls");
            }
        }
    
    
        #region PropertyChanged implementation
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    
    
        #endregion
    
    
    }
    

    MyUserControl.XAML
       <StackPanel>
            <Label Content="{Binding MyLabelContent}" />
          <TextBlock Text="{Binding MyTextBlockContent}" />
     </StackPanel>
    

    我的控制.cs
     public class MyControl
    {
        public string MyLabelContent { get; set; }
        public string MyTextBlockContent { get; set; }
    
    }
    

    希望这对你有用:)

    这是一个工作示例的链接:
    https://drive.google.com/file/d/0B8O-XH0V_o1hNXprX2c0S0xJUFU/view?usp=sharing

    关于c# - 如何从 MainWindow 中的用户控件获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28827503/

    相关文章:

    C# 返回可为空的属性的值

    c# - 用于 WPF 导航的 Window vs Page vs UserControl?

    c# - 如何使用 EF 和 WPF 显示和更新来自多个表的数据网格中的数据?

    android - Xamarin Forms MasterDetail 页面导航导致 Android 崩溃 [致命信号 6 (SIGABRT),代码 -6],适用于 iOS 和 UWP

    WPF:在 MVVM 中管理窗口(打开、关闭等)?

    javascript - PDF4NET 不以 adobe livecycle 形式执行 javascript

    c# - Fluent Nhibernate 按条件映射到不同的列

    c# - ElasticSearch(C#Nest)中的多个最大/最小聚合

    wpf - 使用 DataGridTemplateColumn 对数据网格进行排序

    c# - MVVM - 在 ViewModel 中使用实体