2012-03-16 2 views
0

바인딩이 텍스트 상자에 대해 작동하지만 usercontrol에 대해 작동하지 않는 이유를 알지 못합니다. 아래 이미지에 어떻게 작동하는지 볼 수 있습니다. 이 서비스는 노란색 usercontrol에 바인딩 할 수 있으며이 usercontrol에는 내 클래스의 속성이 포함되어 있습니다. 내 경우에이 속성은 전자 메일입니다. 문제는이 전자 메일이 노란색 usercontrol에 바인딩되지 않는다는 것입니다. 간단한 "TextBox"컨트롤로 usercontrol을 바꾸면 올바르게 작동합니다.datacontext 및 사용자 정의 usercontrol 바인딩을 설정하는 방법

바인딩 작업을 수행하는 방법에 대해 조언 해 주실 수 있습니까? Silvelright 메인 페이지

#Region "UserProfile" 

    ''' <summary> 
    ''' UserProfile Dependency Property 
    ''' </summary> 
    Public Shared ReadOnly UserProfileProperty As DependencyProperty = _ 
     DependencyProperty.Register("UserProfile", GetType(ServiceReference1.UserProfile), GetType(MainPage), _ 
      New Windows.PropertyMetadata(Nothing, _ 
       AddressOf OnUserProfileChanged)) 

    ''' <summary> 
    ''' Gets or sets the UserProfile property. This dependency property 
    ''' indicates .... 
    ''' </summary> 
    Public Property UserProfile() As ServiceReference1.UserProfile 
     Get 
      Return CType(GetValue(UserProfileProperty), ServiceReference1.UserProfile) 
     End Get 
     Set(ByVal value As ServiceReference1.UserProfile) 
      SetValue(UserProfileProperty, value) 
     End Set 
    End Property 

    ''' <summary> 
    ''' Handles changes to the UserProfile property. 
    ''' </summary> 
    Private Overloads Shared Sub OnUserProfileChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs) 
     Dim target As MainPage = CType(d, MainPage) 
     Dim oldUserProfile As ServiceReference1.UserProfile = CType(e.OldValue, ServiceReference1.UserProfile) 
     Dim newUserProfile As ServiceReference1.UserProfile = target.UserProfile 
     target.OnUserProfileChanged(oldUserProfile, newUserProfile) 
    End Sub 

    ''' <summary> 
    ''' Provides derived classes an opportunity to handle changes to the UserProfile property. 
    ''' </summary> 
    Protected Overridable Overloads Sub OnUserProfileChanged(ByVal oldUserProfile As ServiceReference1.UserProfile, ByVal newUserProfile As ServiceReference1.UserProfile) 
     Me.DataContext = newUserProfile 

    End Sub 

#End Region 

User control description of binding

Codebehind가 재산을 추적은 "newUserProfile"항목은 코드 숨김에서 성공적으로 설정되었다.

이메일의 결합으로 XAML

<UserControl x:Class="CH_App.ucUserEditor" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
          xmlns:my="clr-namespace:CH_App" 

    mc:Ignorable="d" 
    d:DesignHeight="300" d:DesignWidth="400"> 

    <Grid x:Name="LayoutRoot" Background="White"> 
     <TextBox Text="{Binding Path=Email}"/> 
     <my:ucDbRow Title="Email" Value="{Binding Path=Email, Mode=TwoWay}" /> 
    </Grid> 
</UserControl> 

Texbox는해야처럼 작동 및 이메일 주소를 보여줍니다. usercontrol에 전자 메일 주소가 표시되지 않습니다. 사용자 정의 컨트롤에 제목이 올바르게 표시됩니다.

UserControl을

<UserControl x:Class="CH_App.ucDbRow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:my="clr-namespace:CH_App" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
      DataContext="{Binding RelativeSource={RelativeSource Self}}" 
    d:DesignHeight="300" d:DesignWidth="400"> 

    <StackPanel> 
     <TextBlock x:Name="txtTitle" Text="{Binding Path=Title}" /> 
     <TextBox x:Name="txtValue" Text="{Binding Path=Value, Mode=TwoWay}"/> 
    </StackPanel> 
</UserControl> 

UserControl을의 Codebehind가

#Region "Title" 

    ''' <summary> 
    ''' Title Dependency Property 
    ''' </summary> 
    Public Shared ReadOnly TitleProperty As DependencyProperty = _ 
     DependencyProperty.Register("Title", GetType(String), GetType(ucDbRow), _ 
      New Windows.PropertyMetadata("")) 

    ''' <summary> 
    ''' Gets or sets the Title property. This dependency property 
    ''' indicates .... 
    ''' </summary> 
    Public Property Title() As String 
     Get 
      Return CType(GetValue(TitleProperty), String) 
     End Get 
     Set(ByVal value As String) 
      SetValue(TitleProperty, value) 
     End Set 
    End Property 

#End Region 



#Region "Value" 

    ''' <summary> 
    ''' Value Dependency Property 
    ''' </summary> 
    Public Shared ReadOnly ValueProperty As DependencyProperty = _ 
     DependencyProperty.Register("Value", GetType(String), GetType(ucDbRow), _ 
      New Windows.PropertyMetadata("")) 

    ''' <summary> 
    ''' Gets or sets the Value property. This dependency property 
    ''' indicates .... 
    ''' </summary> 
    Public Property Value() As String 
     Get 
      Return CType(GetValue(ValueProperty), Object) 
     End Get 
     Set(ByVal value As String) 
      SetValue(ValueProperty, value) 
     End Set 
    End Property 

#End Region 
+0

이 질문은 WPF 질문입니까, 아니면 Silverlight 질문입니까? – NVM

+0

저는 Silverlight를 연구하고 있습니다. 하지만 지난 달 WPF에서 비슷한 문제가 있었지만 거기에 바인딩없이 해결 방법을했습니다. 이제 확신하기 때문에 그것을 고치고 싶습니다. 나는 작은 선언을 놓친 것입니다. 나는 이제 여러 바인딩 키워드로 몇 시간을 보았지만 결코 성공하지 못했습니다. – Nasenbaer

+0

나는 두 번 질문을 읽었지만 여전히하려고하는 것을 얻지 못한다. 먼저 달성하고자하는 것에 대한 세부 사항을 제공하십시오. – NVM

답변

1

편집 (삽입) :

당신은 실버 라이트 4를 사용하고, 나는이었다 중 테스트에 Silverlight 5 또는 WPF from b 아마도 oth 일 수도 있지만
WPF는 RelativeSourceBinding을 확실히 지원합니다. 그러나 거의 옳았습니다.
올바른 경우 Visual Studio의 출력 창에 다음 오류가 표시됩니다.

System.Windows.Data Error: BindingExpression path error:
'Email' property not found on 'VisualBasicSilverlightApplication1.ucDbRow'
'VisualBasicSilverlightApplication1.ucDbRow' (HashCode=72766).
BindingExpression: Path='DataContext.Email'
DataItem='VisualBasicSilverlightApplication1.ucDbRow' (HashCode=72766);
target element is 'VisualBasicSilverlightApplication1.ucDbRow' (Name='');
target property is 'Value' (type 'System.String')..

DataContext는 usercontrol의 최상위/인스턴스를 제외하고는 usercontrol을 통해 전달됩니다.
그래서 대신이 일을 :

<my:ucDbRow Title="Email" Value="{Binding Path=Email, Mode=TwoWay}" /> 

코드에서 변경해야 할 수있는 유일한 것은이 LayoutRoot 대부분의 시간을 당신이에 DataContext를 설정 요소에 지점입니다 :

<my:ucDbRow Title="Email" Value="{Binding ElementName=LayoutRoot, 
      Path=DataContext.Email, Mode=TwoWay}" /> 

이전 대답 (ucUserEditor에서)
당신은 CH_App.ucDbRow이 DataContext="{Binding RelativeSource={RelativeSource Self}}"와 바인더 제본 데이터 컨텍스트를 재정의 . 그것을 제거하면 가치가 작동합니다. 왜냐하면 당신의 밑바닥이 DataContext이지만 광고 제목이 더 이상 작동하지 않기 때문입니다.이것에

변경 ucDbRow :

<UserControl x:Class="CH_App.ucDbRow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    d:DesignHeight="300" d:DesignWidth="400"> 
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding}"> 
    <StackPanel> 
     <TextBlock x:Name="txtTitle" Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=Title}" Height="23"/> 
     <TextBox x:Name="txtValue" Text="{Binding Path=Value, Mode=TwoWay}"/> 
    </StackPanel> 
    </Grid> 
</UserControl> 

참고 :

해결책이 바인딩이 작동하지 않는 경우 그것이 출력 창에있어 실패 할 경우, 당신의 OUPUT 창을 확인합니다. 또한

:

나는 하지가 컨트롤의 같은 UserControl을의의를 사용하는 것이 좋습니다 것입니다. 제 의견으로는 사용자 정의 컨트롤이 개별 컨텍스트를 표현하는 데 더 많이 사용되어야합니다. 사용자 콘트롤을 페이지로 더보기 시작하고 자세한 작업을 위해 사용자 정의 컨트롤과 데이터 템플릿을 사용하십시오. 또한 더 나은 레이아웃을 구축하는 것은 WPF와 Silverlight에서 가장 좋은 기능 중 하나 인 (다시 생각해 보면) Grid을 사용하면 매우 쉬워지고 있습니다. 주문한 usercontrols에 맞을 수는 없습니다.

+0

안녕하세요, Silvermind. 귀하의 답변에 감사드립니다. 나는 당신과 함께 usercontrols 있지만 여기에 모두 설명한다면 그것은 질문을 확장합니다. 나는 또한 질문을 위해서만 stackpanel을했다. 나는 AncestorType을 사용하여 새롭고 Silverlight XAML ucDbRow를 입력 할 때 AncestorType이 상대 소스로 발견되지 않았을 때 이미 오류 메시지가 나타납니다. 어떤 충고? – Nasenbaer

+0

@ Nasenbaer 네임 스페이스가 필요하기 때문에. xmnls : local = "clr-namespace : mynamespace"및 Ancestortype = "{x : Type local : ucDbRow}" – Silvermind

+0

Btw : ucDbRow가 UserControl 인 경우 (예를 xaml로 표시 한 경우 예라고 가정) 단어'UserControl'을'AncestorType'으로 정의합니다. – Silvermind

관련 문제