2012-08-17 33 views
9

Tôi có một UserControl với một lớp ViewModel như DataContext:Binding đến nội ViewModel-tài sản

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 lớp:

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

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

Nếu tôi đặt ViewMod elProperty cho công chúng ràng buộc hoạt động tốt. Nhưng nếu tôi thiết lập các tài sản nội bộ như trên ràng buộc không thành công (Ràng buộc lỗi: tài sản không tìm thấy ...).

Tôi nghĩ rằng một thuộc tính nội bộ có thể truy cập như công khai trong cùng một hội đồng. Ngoài ra tôi có thể truy cập vào tài sản từ UserControl-codebehind mà không gặp bất kỳ sự cố nào:

{ 
... 

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

... 

Bất kỳ giải thích nào cho hành vi này?

Cảm ơn trước, rhe1980

+0

Bạn nên đã lấy một cái nhìn trên tài liệu DataBinding trước. – HichemSeeSharp

Trả lời

19

Như đã nêu 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.

+0

cảm ơn câu trả lời của bạn! Tôi nghĩ trong quan điểm của tài sản là như nhau nếu lớp là công khai và tài sản là nội bộ như khi lớp là nội bộ và tài sản công cộng. Nhưng dường như liên kết không: -) ... – rhe1980

Các vấn đề liên quan