Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么我不能在绑定中直接使用ObservableCollection_C#_Wpf_Xaml_Data Binding - Fatal编程技术网

C# 为什么我不能在绑定中直接使用ObservableCollection

C# 为什么我不能在绑定中直接使用ObservableCollection,c#,wpf,xaml,data-binding,C#,Wpf,Xaml,Data Binding,我想知道为什么我不能直接使用MainWindow.xaml中的ObservableCollection 代码: 公共部分类主窗口:窗口 { 公共ObservableCollection tmpLst=新的ObservableCollection(); 公众可观察收集假人 { 获取{return tmpLst;} } 私有void CreateDummy() { 对于(int x=1;x

我想知道为什么我不能直接使用MainWindow.xaml中的ObservableCollection

代码:

公共部分类主窗口:窗口
{
公共ObservableCollection tmpLst=新的ObservableCollection();
公众可观察收集假人
{
获取{return tmpLst;}
}
私有void CreateDummy()
{
对于(int x=1;x<10;x++)
{
添加(新的DummyData(){text=(“DummyData=”+x),wert=x});
}
}
公共主窗口()
{            
初始化组件();
CreateDummy();
}
}
Xaml:


Xaml-工作原理:

<DataGrid Name="testGrid"
          AutoGenerateColumns="True" 
          DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
          ItemsSource="{Binding Dummy}"/>


如果我使用的是虚拟的,而不是tmpLst,网格会显示数据,也许我遗漏了什么或者忘记了什么

你什么都没错过


绑定引擎要求绑定目标是属性。绑定到字段永远不会工作。

要使绑定正常工作,必须使用属性而不是公共字段

WPF中有一个称为依赖属性的概念

属性在WPF中具有极其重要的意义

几个好链接:


因为它必须是属性而不是字段。
<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication2"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid Name="testGrid" AutoGenerateColumns="True" 
              DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
              ItemsSource="{Binding tmpLst}"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch">
    </DataGrid>
</Grid>
<DataGrid Name="testGrid"
          AutoGenerateColumns="True" 
          DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
          ItemsSource="{Binding Dummy}"/>