WPF 绑定:由于未知的数据上下文而无法解析符号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16936710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:55:59  来源:igfitidea点击:

WPF Binding: cannot resolve symbol due to unknown datacontext

c#wpfdata-bindingwpfdatagrid

提问by juergen d

I try to bind a CheckBox in a DataGrid but in the designer I get while hovering over DoImport

我尝试在 DataGrid 中绑定一个 CheckBox 但在设计器中我在悬停时得到 DoImport

cannot resolve symbol 'DoImport' due to unknown datacontext

由于未知的数据上下文,无法解析符号“DoImport”

My code is

我的代码是

<Window x:Class="MyWindow">
  <Grid>
    <DataGrid x:Name="MyGrid" ItemsSource="{Binding}">
        <DataGrid.Columns>
            <DataGridCheckBoxColumn Header="Import" 
                   Binding="{Binding Path=DoImport, 
                             Mode=TwoWay, 
                             UpdateSourceTrigger=PropertyChanged}" />
        </DataGrid.Columns>
    </DataGrid>
  </Grid>
</Window>

public partial class MyWindow : Window, INotifyPropertyChanged {
    public MyWindow(ObvervableCollection<Part> parts) {
        _parts = parts;
        MyGrid.DataContext = _parts;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string name) {
        if (PropertyChanged != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

    private ObservableCollection<Part> _parts;
    public ObservableCollection<Part> Parts {
        get { return _parts; }
        set
        {
            _parts = value;                    
            OnPropertyChanged("Parts");
        }
    }
}

The _partsis a collection of items that fill the DataGrid. The Partclass is:

_parts是占满DataGrid项目的集合。该Part班是:

public class Part {
    public bool DoImport { get; set; }
}

采纳答案by Egi

The designer cannot supply a ObvervableCollection<Part>instance to the MyWindow constructor, because it does not know how. so your constructor should never be called in the designer. that is why the designer "cannot resolve symbol 'DoImport' due to unknown datacontext". the designer in visual studio expects a parameter-less default constructor in order to work properly.

设计器无法ObvervableCollection<Part>为 MyWindow 构造函数提供实例,因为它不知道如何提供。所以你的构造函数永远不应该在设计器中被调用。这就是为什么设计者“由于未知的数据上下文而无法解析符号‘DoImport’”。Visual Studio 中的设计师需要一个无参数的默认构造函数才能正常工作。

maybe you should check that out: http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/sample-data-in-the-wpf-and-silverlight-designer.aspxor better yet ... let blend create design sample data for you.

也许您应该检查一下:http: //blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/sample-data-in-the-wpf-and-silverlight-designer.aspx或更好。 .. 让 blend 为您创建设计示例数据。