【问题标题】:Binding to internal ViewModel-Property绑定到内部 ViewModel-Property
【发布时间】:2012-08-17 11:09:17
【问题描述】:

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

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>

代码隐藏:

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

ViewModel 类:

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

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

如果我将 ViewModelProperty 设置为 public,则绑定可以正常工作。但是如果我像上面一样将属性设置为内部绑定失败(绑定错误:找不到属性...)。

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

{
...

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

...

对这种行为有什么解释吗?

提前致谢, rhe1980

【问题讨论】:

  • 您之前应该看过 DataBinding 文档。

标签: c# wpf xaml data-binding internal


【解决方案1】:

如上所述here

您用作绑定源属性的属性必须 成为您班级的公共财产。明确定义的接口 不能出于绑定目的访问属性,也不能受保护, 没有基础的私有、内部或虚拟属性 实施。

【讨论】:

  • 感谢您的回答!我认为如果类是公共的并且属性是内部的,那么从属性的角度来看是相同的,就像类是内部的并且属性是公共的一样。但似乎链接不是:-)...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
  • 2019-01-18
  • 1970-01-01
  • 2015-03-21
  • 2010-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多