使用数据绑定、数据模板和可观察集合的 C# WPF 应用程序

Posted

技术标签:

【中文标题】使用数据绑定、数据模板和可观察集合的 C# WPF 应用程序【英文标题】:C# WPF application using data binding, data templates and observable collection 【发布时间】:2014-10-06 20:07:43 【问题描述】:

我正在使用数据绑定、数据模板和可观察集合在 C# WPF 中制作程序。我的应用程序基于来自http://msdn.microsoft.com/en-us/library/vstudio/ms771319(v=vs.90).aspx 的数据绑定演示。出于某种原因,我无法让我的程序显示任何来自绑定的数据。调试告诉我,我的 Records 类集合有效,但在这一行:

records_collection_db = (CollectionViewSource)(this.Resources["records_collection_db"]);

我的“records_collection_db”变量为空,而它应该保存一些数据。我怀疑我在 xaml 行中的 CollectionViewSource 设置不正确,但我真的不知道如何修复它。这是我在 WPF 中的第一个程序,所以我在这方面没有太多经验。目前,我的代码与示例代码之间唯一可见的区别是我的初始窗口是......在演示中它是一个

代码(或至少是它的缩短版):


记录等级

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace WpfApplication1

    public class Record : INotifyPropertyChanged
    
        private int Lp;
        private string group;

        public event PropertyChangedEventHandler PropertyChanged;

        public int _Lp
        
            get  return this.Lp; 
            set  this.Lp = value; OnPropertyChanged("_Lp"); 
        

        public string _group
        
            get  return this.group; 
            set  this.group = value; OnPropertyChanged("_group"); 
        


        public Record(int Lp, string group)
        
            this.Lp = Lp;
            this.group = group;
        

        protected void OnPropertyChanged(string property)
        
            if (PropertyChanged != null)
            
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            
        
    


初始窗口

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Configuration;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1

    public partial class MainWindow : Window
                    
        public MainWindow()
        
            InitializeComponent();

            var newWindow1 = new Audyt_window();
            newWindow1.Show();
            
    


<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:WpfApplication1" 
        xmlns:System="clr-namespace:System;assembly=Mscorlib"
        Title="MainWindow" Height="350" Width="525"
        WindowStartupLocation="CenterScreen"
        >
    <Window.Resources>
        <Style x:Key="text_style" TargetType="TextBlock">
            <Setter Property="Foreground" Value="#333333" />
        </Style>        

    </Window.Resources>    

    <Grid>
        <Button Content="Start" HorizontalAlignment="Left" Margin="36,36,0,0" VerticalAlignment="Top" Width="178" Height="93" Click="Button_Click"/>
        <Button Content="Zamknij" HorizontalAlignment="Left" Margin="202,223,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
        <Button Content="Rekordy" HorizontalAlignment="Left" Margin="318,56,0,0" VerticalAlignment="Top" Width="108" Height="52" Click="Button_Click_2" />
        <Button Content="Dodaj" HorizontalAlignment="Left" Margin="351,157,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_3"/>
    </Grid>
</Window>

操作窗口

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.ComponentModel;


namespace WpfApplication1

    public partial class Audyt_window : Window
           
        CollectionViewSource records_collection;

        private ObservableCollection<Record> records = new ObservableCollection<Record>();
        public ObservableCollection<Record> Records
        
            get  return this.records; 
            set  this.records = value; 
        

        public Audyt_window()
                
            load_temp_data();    

            InitializeComponent();
            records_collection = (CollectionViewSource)(this.Resources["records_collection"]);
        

        private void load_temp_data()
        
            Record rek1 = new Record(601, "Gr1", "Pro1", "Pyt1", 600001, "Kat1", false, false);
            Record rek2 = new Record(602, "Gr2", "Pro2", "Pyt2", 600002, "Kat2", false, false);
            Record rek3 = new Record(603, "Gr3", "Pro3", "Pyt3", 600003, "Kat3", false, false);
            this.Records.Add(rek1);
            this.Records.Add(rek2);
            this.Records.Add(rek3);
                    
    


<Window x:Class="WpfApplication1.Audyt_window"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Audyt" 
        xmlns:src="clr-namespace:WpfApplication1" 
        ResizeMode="NoResize"
        SizeToContent="WidthAndHeight"
        WindowStartupLocation="CenterScreen"
        >

    <Window.Resources>
        <CollectionViewSource Source="Binding Source=x:Static Application.Current, Path=Records" x:Key="records_collection" />

        <Style x:Key="text_style" TargetType="TextBlock">
            <Setter Property="Foreground" Value="#333333" />
        </Style>

        <DataTemplate x:Key="Records_Template" DataType="x:Type src:Record">
            <Border BorderThickness="2" BorderBrush="Navy" Padding="7" Name="Record_List_Border" Margin="3" Width="345">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="20"/>
                        <ColumnDefinition Width="30"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Background="Aqua" Grid.Row="0" Grid.Column="0"
                               Name="textblock_Lp"
                               Style="StaticResource text_style"
                               Text="Lp: "
                               >
                    </TextBlock>
                    <TextBlock Background="Azure" Grid.Row="0" Grid.Column="1"
                               Name="datablock_Lp"
                               Style="StaticResource text_style"
                               Text="Binding Path=_Lp"
                               >
                    </TextBlock>
                    <TextBlock Background="Aqua" Grid.Row="0" Grid.Column="2"
                               Name="datablock_group"
                               Style="StaticResource text_style"
                               Text="Binding Path=_group"
                               >
                    </TextBlock>

                </Grid>
            </Border>
        </DataTemplate>

    </Window.Resources>

    <Border Padding="10">
        <Grid>

            <ListBox Name="Hits_View_List" HorizontalAlignment="Left" VerticalAlignment="Top" 
                 Height="525" Width="400" Margin="420,0,0,0" 
                 BorderThickness="2" BorderBrush="DimGray" 
                 ItemsSource="Binding Source=StaticResource records_collection"             
                 >                    
            </ListBox>

        </Grid>
    </Border>
</Window>

【问题讨论】:

应该有records_collection = (CollectionViewSource)(this.Resources["records_collection"]);在我的帖子中。 【参考方案1】:

在您的Audyt_window 中,您将CollectionViewSource 的绑定源设置为x:Static Application.Current,但Records ObservableCollection 在您的Audyt_window 中声明

变化:

<CollectionViewSource Source="Binding Source=x:Static Application.Current, Path=Records" x:Key="records_collection" />

<CollectionViewSource Source="Binding RelativeSource=RelativeSource FindAncestor, AncestorType=Window, Path=Records" x:Key="records_collection" />

我认为它应该可以工作。

【讨论】:

谢谢!这就是修复它的原因!【参考方案2】:

你命名你的 collectionviewsource

x:Key="records_collection"

而您正在搜索无法匹配的records_collection_db...

records_collection_db = (CollectionViewSource)(this.Resources["records_collection_db"]);

更改密钥或将字符串更改为正确的名称

【讨论】:

感谢您的快速响应。不幸的是,这只是我写这篇文章时的拼写错误,而不是真正的问题;/ 但失败出现在文本和Operational window的代码中

以上是关于使用数据绑定、数据模板和可观察集合的 C# WPF 应用程序的主要内容,如果未能解决你的问题,请参考以下文章

刷新 WPF Datagrid 未绑定到可观察集合?

c# wpf datagrid 模板列修改某个单元格,更新所选行另一个单元格的值,如何做到呢?

如何将 TabControl 的项目绑定到 wpf 中的可观察集合?

Xceed WPF Toolkit - BusyIndi​​cator - 在 C# 中创建动态加载消息,数据模板中的数据绑定

WPF 数据网格绑定工具提示在表格内容绑定刷新时闪烁

使用 Android MVVM 查看数据绑定集合