2014-02-28 4 views
0

XAML에 바인딩하려는 일부 속성이있는 UserControl이 있습니다.UserControl 데이터 바인딩 속성이 작동하지 않습니다.

<UserControl x:Class="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" DataContext="{RelativeSource Self}"> 
<UserControl.Background> 
    <ImageBrush ImageSource="{Binding BackgroundImage}" Stretch="UniformToFill" AlignmentX="Center" AlignmentY="Bottom"/> 
</UserControl.Background> 

<Grid Name="mainGrid"> 
    <Label Canvas.ZIndex="-1" Foreground="Gray" Content="{Binding VersionNumber}" Height="28" HorizontalAlignment="Left" Name="versionLabel" VerticalAlignment="Bottom" /> 
</Grid> 
</UserControl> 

그리고 코드 숨김 :

public partial class UserControl1 : UserControl, INotifyPropertyChanged 
{ 
    public string VersionNumber { private get; set; } 
    public ImageSource BackgroundImage { private get; set; } 

    public UserControl1() 
    { 
     InitializeComponent(); 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
    } 

} 

내가 그렇게

<Window x:Class="MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:SomeNameSpace" 

     Title="MainWindow" 
     MinHeight="400" MinWidth="400" > 
<local:UserControl1 BackgroundImage="images\background.png" VersionNumber="10"/> 
물론

같은 UserControl에 포함 된 창을 가지고, 실제 윈도우가 표시되지 않습니다 배경이 비어 있고 Label.Content이 null이지만 자동차 창에 이렇게 속성이 올바르게 설정되었습니다. Autos

저는 지난 2 시간 동안이 작업을 망쳤습니다. 무엇이 잘못 됐는지 모릅니다.

편집 나는이

private string versionNumber; 
public string VersionNumber { get { return this.versionNumber; } 
set { 
     this.versionNumber = value; 
     OnPropertyChanged("VersionNumber"); 
    } 
} 

을 시도하고 그것은 여전히,이 경우 레이블이 업데이트되지 않습니다 작동하지 않습니다. 내가 제대로하지 않은 느낌이

result

+0

에게 제대로 설정되어 있지 않은 경우 때문에 데이터 컨텍스트 문제가 될 수 있습니다 속성 집합의 OnPropertyChange ("yourpropertyname")가 누락되었습니다. –

+0

당신의 속성의 설정자를 public으로 변경하려고 시도하고 그 것이 문제를 해결하는지 확인하십시오. – har07

+1

@ har07 setter는 공개되어 있고, 그 개인은 게터입니다. @MihaiHantea 업데이트보기, 여전히 'OnPropertyChanged()'를 호출해도 작동하지 않습니다. – ron975

답변

1

라벨 바인딩에 이것을 사용해야합니다 :

Content={Binding RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type wpfApplication1:UserControl1}}, Path=VersionNumber} 

UserControl1은 사용자 정의 컨트롤 클래스의 이름입니다. 네임 스페이스와 사용자 정의 컨트롤을 지정해야합니다.

비공개로 유지하면이 바인딩으로 계속 사용할 수 있습니다.

//window.xaml

<Window x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:wpfApplication1="clr-namespace:WpfApplication1" 
    Title="MainWindow" Height="350" Width="525"> 
<Grid> 
    <wpfApplication1:UserControl1 VersionNumber="10"/> 
</Grid> 

// UserControl1을

<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" 
     xmlns:wpfApplication1="clr-namespace:WpfApplication1" 
     mc:Ignorable="d" 
     d:DesignHeight="300" d:DesignWidth="300" DataContext="{RelativeSource Self}"> 
<UserControl.Background> 
    <ImageBrush ImageSource="{Binding BackgroundImage}" Stretch="UniformToFill" AlignmentX="Center" AlignmentY="Bottom"/> 
</UserControl.Background> 

<Grid Name="mainGrid"> 
    <Label Canvas.ZIndex="-1" Foreground="Gray" Content="{Binding RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type wpfApplication1:UserControl1}}, Path=VersionNumber}" 
      Height="28" HorizontalAlignment="Left" Name="versionLabel" VerticalAlignment="Bottom" /> 
</Grid> 

:이 데모를 만든 코드에 따라

편집

UserControl1.CS

public partial class UserControl1 : UserControl, INotifyPropertyChanged 
{ 
    private string _versionNumber; 
    private ImageSource _backgroundImage; 

    public UserControl1() 
    { 
     InitializeComponent(); 
    } 

    public string VersionNumber 
    { 
     private get { return _versionNumber; } 
     set 
     { 
      _versionNumber = value; 
      OnPropertyChanged("VersionNumber"); 
     } 
    } 

    public ImageSource BackgroundImage 
    { 
     get { return _backgroundImage; } 
     set 
     { 
      _backgroundImage = value; 
      OnPropertyChanged("BackgroundImage"); 
     } 
    } 


    public event PropertyChangedEventHandler PropertyChanged; 
    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

@anees 당신도의 versionNumber와 backgroundImage의에 대한 종속성 속성을 사용할 수 있습니다 제안으로 :

public static readonly DependencyProperty VersionNumberProperty = DependencyProperty.Register(
     "VersionNumber", typeof (string), typeof (UserControl1), new PropertyMetadata(default(string))); 

    public string VersionNumber 
    { 
     get { return (string) GetValue(VersionNumberProperty); } 
     set { SetValue(VersionNumberProperty, value); } 
    } 

public static readonly DependencyProperty BackgroundImageProperty = DependencyProperty.Register(
     "BackgroundImage", typeof (ImageSource), typeof (UserControl1), new PropertyMetadata(default(ImageSource))); 

    public ImageSource BackgroundImage 
    { 
     get { return (ImageSource) GetValue(BackgroundImageProperty); } 
     set { SetValue(BackgroundImageProperty, value); } 
    } 
+0

위대한,이 정말 잘 작동합니다, 감사합니다! – ron975

0

는 당신의 MainWindow를

xmlns:local="clr-namespace:YourNameSpace" 

에 다음 네임 스페이스를 포함 그리고 다음과 같이 당신의 UserControl을 추가 MainWindow를에 해당 UserControl이 포함

<local:UserControl1 x:Name="somename" .... /> 
+0

어쨌든, xmlns를 추가하여 질문을 업데이트했습니다. 그러나 데이터 바인딩은 여전히 ​​작동하지 않습니다. – ron975

+0

종속성 속성을 설정하려고 시도 했습니까? http://wpftutorial.net/DependencyProperties.html –

0

그 쇼의 널 (null)이 다음 상황에 맞는이

관련 문제