c# - 对象引用未设置到对象实例,在 WPF 设计器中,位于 x :Reference

标签 c# wpf xaml mvvm dependency-properties

首先,我当然知道这是要问的最重复的问题之一……为了节省您的时间,我会说这是一个转折点。

首先,设置

<UserControl {d:DesignInstance Type=MyControl, IsDesignTimeCreatable=True}>
    <Grid x:Name="root">
        <FrameElement x:Name="ContextProxy" Visibility="Collapsed" />
        ...
        <DataGridTextColumn.Visibility>
            <!-- squiggly line on the SOURCE part -->
            <Binding Source="{x:Reference Name=ContextProxy}"
                     Path=DataContext.IncludeThisColumn
                     />
        </DataGridTextColumn.Visibility>
    </Grid>
</UserControl>

代码隐藏

public partial class MyControl {

    // viewmodel for INPC (data lookups, child controls, etc)
    public ViewModels.vmMyControl { get; } = new ViewModels.vmMyControl();

    MyControl() { // ctor
        this.root.DataContext = this; // to support DependencyProperty
    }

    // several dependency properties for external use/bindings
    public static DP IncludeThisColumnDP = DP.Register(..., OnIncludeThisColumnChanged)
    public bool IncludeThisColumn { GetValue(DP); } { SetValue(DP, value); }

    // relay DP changes from parent / outside world, to internal ViewModel
    private void OnIncludeThisColumnChanged(..)
    { (o as vmMyControl).ViewModel.IncludeThisColumn = e.NewValue; }
}

View 模型

public class vmMyControl {

    private readonly myObservableINPC<bool> _IncludeThisColumn;
    public bool IncludeThisColumn { get/set for _IncludeThisColumn.Value }

    public vmMyControl() { // ctor
        // initialize INPC crap
        this.IncludeThisColumn = new blah(nameof(IncludeThisColumn));

        // data for designer
        if (...GetIsInDesignMode)
            Data_LoadMock();
    }

    public Data_LoadMock() {
        // populate some of the data points
    }
}

所以一般来说,我认为我正在遵循最佳实践(除了 DP/INPC 的混合,但它很好地满足了我的需求,所以无论如何)...

  • 用户控件的数据上下文应用于内部根元素(顶级网格)

  • 数据上下文设置为用户控件的实例以启用 DP。

  • 用户控件实例具有初始化为 ViewModel 的只读属性

  • viewmodel 使用 GetIsInDesignMode 来确保不加载数据(实际上,代码的 DAL 代理还会检查内部 bool 值以指示它们何时作为单元测试运行,以进一步确认它们已被禁用, 与 InternalsVisibleTo(UnitTestProject))

  • 由于无法直接绑定(bind)数据网格列的可见性(不能在元素树或其他内容中绑定(bind)),我添加了一个 FrameworkElement 来充当数据上下文的代理


扭曲

所以,首先让我说,在运行时,代码是有效的。所有绑定(bind)、数据加载等。无一异常(exception)。这纯粹是一个设计时问题,但它让我很烦恼。

由于我知道处理 w/WPF 设计模式时的空引用问题,所以当我看到这个问题时我的第一个 Action 是添加:

MyControlTests.cs

[TestMethod]
public void InstantiateVM() {
    Action a = () => { return new vmMyControl(); }
    a.ShouldNotThrow(); // FluentAssertions
}

[TestMethod]
public void InstantiateUC() {
    Action a = () => { return new MyControl(); }
    a.ShouldNotThrow(); // FluentAssertions
}

事情是这样的......两个测试都成功运行......并且在检查(调试 + 断点)时,对象中没有任何属性导致异常。


环境

应用程序使用框架 4.5 和 C#6(因为我使用的是 VS2015)

我看到有人发布有关 VS2015 的帖子,将鼠标悬停在消息上以获取更多信息,但它似乎对我没有任何作用。

就其值(value)而言,我正在使用 VS2015 REL... 很想应用更新 2 或 3,但从我听到/读到的内容来看,似乎到处都有一些错误。

最佳答案

根据 http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/

public class BindingProxy : Freezable
{
#region Overrides of Freezable

protected override Freezable CreateInstanceCore()
{
    return new BindingProxy();
}

#endregion

public object Data
{
    get { return (object)GetValue(DataProperty); }
    set { SetValue(DataProperty, value); }
}

// Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty =
    DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

然后

<DataGrid.Resources>
    <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>

<DataGridTemplateColumn.Visibility>
    <Binding Source="{StaticResource ResourceKey=DataContextProxy}"
             Path="Data.IncludeThisColumn"
             Converter="{StaticResource ResourceKey=BoolToHiddenConverter}"
             />
</DataGridTemplateColumn.Visibility>

关于c# - 对象引用未设置到对象实例,在 WPF 设计器中,位于 x :Reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38377622/

相关文章:

c# - Android 上的数据 GridView

c# - 编码——它是什么以及我们为什么需要它?

c# - WPF 拦截全局鼠标移动(就像在 Windows 窗体中使用 IMessageFilter)

WPF MVVM : How to setup binding on user controls?

c# - WPF ListBox WPF XAML 内的顶部对齐

wpf - 在 WrapPanel 内自动调整大小?

c# - 如何在包含 POCO 的域模型程序集中删除对 System.Web.Mvc 的依赖

c# - 在 C# 中将对象列表转换为数组 - "x => x.Name"语法是什么意思?

wpf - 如何在按钮按下时绑定(bind)命令(wpf/mvvm)?

xaml - Windows 10 UWP 中具有自定义附加属性的自适应触发器