2012-04-10 3 views
2

속성 값 상속을 사용하여 창에서 UserControl 위해 노력하고있어. 필자가 아는 한, FrameworkPropertyMetadataOptions.Inherits 옵션과 함께 DependencyProperty를 선언하면이 작업을 수행 할 수 있습니다.속성 값 상속 UserControl 함께 작동하지 않는다

MainWindow.xaml :

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:WpfApplication1" Name="BobWindow"> 
    <Grid> 
     <Label Content="MainWindow" /> 
     <TextBox Height="23" HorizontalAlignment="Left" Margin="85,2,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=Test, ElementName=BobWindow}" /> 
     <my:UserControl1 HorizontalAlignment="Left" Margin="157,108,0,0" x:Name="userControl11" VerticalAlignment="Top" /> 
    </Grid> 
</Window> 
MainWindow.xaml.cs를

:

using System; 
using System.Windows; 

namespace WpfApplication1 
{ 
    public partial class MainWindow : Window 
    { 
     public static readonly DependencyProperty TestProperty = DependencyProperty.RegisterAttached 
      (
       "Test", 
       typeof(String), 
       typeof(MainWindow), 
       new FrameworkPropertyMetadata 
        (
         null, 
         FrameworkPropertyMetadataOptions.Inherits 
        ) 
      ); 
     public String Test 
      { 
       get { return (String)GetValue(TestProperty); } 
       set { SetValue(TestProperty, value); } 
      } 
     public MainWindow() 
     { 
      InitializeComponent(); 
      Test = "Yip!"; 
     } 
    } 
} 

UserControl1.xaml :

<UserControl x:Class="WpfApplication1.UserControl1" 
      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="300" d:DesignWidth="300" Name="BobControl"> 
    <Grid> 
     <Label Content="UserControl1" /> 
     <TextBox Height="23" HorizontalAlignment="Left" Margin="85,2,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=Test, ElementName=BobControl}" /> 
    </Grid> 
</UserControl> 

UserControl1.xaml.cs :

using System; 
using System.Windows; 
using System.Windows.Controls; 

namespace WpfApplication1 
{ 
    public partial class UserControl1 : UserControl 
    { 
     public static readonly DependencyProperty TestProperty = DependencyProperty.RegisterAttached 
      (
       "Test", 
       typeof(String), 
       typeof(UserControl1), 
       new FrameworkPropertyMetadata 
        (
         null, 
         FrameworkPropertyMetadataOptions.Inherits 
        ) 
      ); 
     public String Test 
      { 
       get { return (String)GetValue(TestProperty); } 
       set { SetValue(TestProperty, value); } 
      } 

     public UserControl1() 
     { 
      InitializeComponent(); 
     } 
    } 
} 
,

이것을 달성하기위한 명확한 예를 찾을 수 없었습니다. MainWindow와 UserControl1에서 RegisterAttached를 사용하는 것이 가장 좋습니다. 내가 누락 된 것이 있어야합니다!

UPDATE

내가 임의의 구조 내 컨트롤을 만들 수 있도록하고 싶습니다

트리의 상단에있는 값을 설정하고 기본 값이 조금씩 (DataContext를 작동하는 방법과 유사)이 . TestProperty가 MainWindow 및 UserControl1에 대한 공통 조상 클래스에 없을 때 이것이 가능합니까?

또한 소스 클래스를 참조하는 것을 피하기를 원합니다. 때로는 Window가 될 수도 있지만 다른 경우 Windows Forms에서 호스트 컨트롤이 될 수 있습니다. 이것이 가능한가?

RESOLVE는 내 혼란이 값 상속을 달성하기 위해 연결되지 않은 종속성 속성의 구문을 사용하고자 막아야 생각합니다. 다음, 당신은 속성 값을 상속하고자하는 경우, 마이크로 소프트의 Property Value Inheritance 페이지에 따르면,

string Value = this.Test; 

그러나 :

<Window ... Test="Fred" /> 

그리고 다음과 같은 구문을 사용하여 UserControl을에서 상속 된 값에 액세스 : 나는 다음과 같은 XAML을 사용하고 싶었 그것은 첨부 된 속성을 통해 있어야합니다.

<Window ... my:MainWindow.Test="Fred" /> 

그리고있는 UserControl의 뒤에 내 코드를 같이 보일 것이다 : 코드가 상기에서 제대로 다시 작성하는 경우

다음 내 XAML이 같을 것이다 (정적 게터/세터 방법과, 한 번 속성을 선언) 이 :

string Value = MainWindow.GetTest(this); 

답변

2

실수는 두 번 속성을 선언하는 것입니다. 그냥 MainWindow, UserControl1 또한 선언하십시오. 그런 다음 MainWindow를이 같은 정적 getter 및 setter 메소드를 선언 :

public static string GetTest(DependencyObject obj) 
{ 
    return (String)obj.GetValue(TestProperty);  
} 

public static void SetTest(DependencyObject obj, string value) 
{ 
    obj.SetValue(TestProperty, value); 
} 

여기에 대한 custom attached properties 더 많은 정보를 가져옵니다.UserControl1을가 MainWindow를의 요소 트리에서 어딘가에 때 초기화 된 후

이제 UserControl1을 함께 다음과 같은 일을하려고 :

UserControl1 uc = this; // for example in a UserControl1 event handler 
string test = MainWindow.GetTest(uc); 

편집 : 당신은뿐만 아니라 위해 UserControl1의 속성을 정의 할 수 있습니다 또는 다른 클래스에서 사용할 수 있으며 연결된 속성이기 때문에 해당 클래스는 DependencyObject에서 파생되지 않아도됩니다.

+0

멋지다. 그 방법으로 AddOwner를 사용하는 것보다 더 깨끗합니다 ... – Mitkins

+0

성능에 대한 편집 및 note [this] (http://msdn.microsoft.com/en-us/library/ms753197.aspx#Making_a_Custom_Property_Inheritable)에 유의하십시오. – Clemens

2

어떤 계승 값이 이라는 것은 무엇을 의미하는지 오해 한 것 같습니다.. 컨트롤에 종속성 속성을 설정하면 해당 속성의 값은 내부의 컨트롤에서 동일하게됩니다. 속성 자체를 재 선언 할 필요가 없습니다 (완전히 별개의 다른 속성을 만드는 것).

상속의 예 :

<Window ... 
     xmlns:local="..." 
     local:MainWindow.Test="Lorem Ipsum"> 
    <Button Name="button"/> 

코드에서는 다음 버튼의 값을 얻을 수 있어야하고 윈도우에서와 동일해야합니다.

var test = (string)button.GetValue(MainWindow.TestProperty); 
// test should be "Lorem Ipsum". 
관련 문제