2011-11-02 6 views
2

내가 이런 UserControl을 가지고내 usercontrol 콘텐츠 컨트롤의 속성을 속성에 바인딩하는 방법?

<UserControl x:Class="MySample.customtextbox" 
     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" 
     d:DesignHeight="20" d:DesignWidth="300"> 
<Grid> 
     <TextBox x:Name="Ytextbox" Background="Yellow"/> 
</Grid> 
</UserControl> 

내가 MVVM 패턴에서 내 컨트롤을 사용하려면를 ... 나는 Ytextbox 텍스트 속성

<CT:customtextbox ?(Ytextbox)Text ="{binding mypropertyinviewmodel}"/> 

내 뷰 모델의 속성을 결합 할 수 있다고합니다. ..내가 어떻게 해?

답변

5

UserControl에서 속성을 만들어 TextBox의 텍스트에 내부적으로 바인딩해야합니다.

<UserControl Name="control" ...> 
    <!-- ... --> 
     <TextBox Text="{Binding Text, ElementName=control}" 
       Background="Yellow"/> 
public class customtextbox : UserControl 
{ 
    public static readonly DependencyProperty TextProperty = 
     TextBox.TextProperty.AddOwner(typeof(customtextbox)); 
    public string Text 
    { 
     get { return (string)GetValue(TextProperty); } 
     set { SetValue(TextProperty, value); } 
    } 
} 

사용법 :

<CT:customtextbox Text="{Binding mypropertyinviewmodel}"/> 

(당신의 DataContext가 될 것으로 기대 모든 외부 바인딩을하지 않으려면 자신에게 해당 UserControl의 DataContext를 설정하지 마십시오 상속 됨, 내부 바인딩의 경우 ElementName 또는 RelativeSource 사용)

+0

'TextBox' 속성 이름과 사용자 정의 컨트롤 propery가 동일하고 다른 속성 이름을 의도했기 때문에 조금 혼란 스러웠습니다.하지만 변경된 사항을 깨닫고 나서 :) +1 감사합니다. – OscarRyz

관련 문제