wpf 绑定到内部 ViewModel-Property

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12004642/
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 05:00:01  来源:igfitidea点击:

Binding to internal ViewModel-Property

c#wpfxamldata-bindinginternal

提问by rhe1980

I have a UserControl with a ViewModel class as DataContext:

我有一个带有 ViewModel 类的 UserControl 作为 DataContext:

XAML

XAML

<UserControl x:Class="DotfuscatorTest.UserControl.View.UserControlView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" >    
<StackPanel>
  <TextBox Text="{Binding ViewModelProperty}"/>
</StackPanel>
</UserControl>

CodeBehind:

代码隐藏:

namespace DotfuscatorTest.UserControl.View
{
   using ViewModel;
   public partial class UserControlView
   {
      public UserControlView()
      {
         InitializeComponent();
         DataContext = new UserControlViewModel();         
      }
   }
}

ViewModel class:

视图模型类:

namespace DotfuscatorTest.UserControl.ViewModel
{
   public class UserControlViewModel
   {
      private string viewModelProperty = "hello world";

      internal string ViewModelProperty
      {
        get { return viewModelProperty; }
        set { viewModelProperty = value; }
      }
   }
}

If I set the ViewModelProperty to public the binding works fine. But if I set the property to internal like above the binding fails (Binding error: property not found... ).

如果我将 ViewModelProperty 设置为 public,则绑定工作正常。但是,如果我将属性设置为内部,则绑定失败(绑定错误:未找到属性...)。

I thought an internal property is accessible like public in same assembly. Also I can access to the property from UserControl-codebehind without any problem:

我认为在同一个程序集中可以像 public 一样访问内部属性。我也可以毫无问题地从 UserControl-codebehind 访问该属性:

{
...

((UserControlViewModel)DataContext).ViewModelProperty = "hallo viewmodel";

...

Any explenation for this behavior?

这种行为的任何解释?

Thanks in advance, rhe1980

提前致谢,rhe1980

回答by JleruOHeP

As stated here

如前所述这里

The properties you use as binding source properties for a binding must be public properties of your class. Explicitly defined interface properties cannot be accessed for binding purposes, nor can protected, private, internal, or virtual properties that have no base implementation.

您用作绑定的绑定源属性的属性必须是您的类的公共属性。不能出于绑定目的访问显式定义的接口属性,也不能访问没有基本实现的受保护、私有、内部或虚拟属性。