c# - 绑定(bind)到内部 ViewModel-Property

标签 c# wpf xaml data-binding internal

我有一个带有 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();         
      }
   }
}

View 模型类:

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

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

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

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

{
...

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

...

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

提前致谢, rhe1980

最佳答案

如前所述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.

关于c# - 绑定(bind)到内部 ViewModel-Property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12004642/

相关文章:

c# - 传递给 C# 中的属性时对象变为空

c# - 我如何模拟我的网络服务?

.net - 从绑定(bind)到 VM 的 CodeBehind 触发 RelayCommand

xaml - 自定义 Windows Phone 8.1 消息对话框

c# - 在 XAML 中访问代码隐藏变量

c# - 如何使用 Application.Resources 中定义的 DataTemplate?

c# - 仅写入一个 XML 属性,而不影响其余属性

c# - 国际化的最佳实践 : What is the best way to store exception/error or informational messages in C#.net?

c# - 无论选择什么,ComboBox都会显示System.Data.DataRowView。 ItemTemplate问题

c# - 将 true/false 更改为图像