2011-08-13 9 views
2

これはかなり簡単だと思っていましたが、明らかに目立たないものを見逃しているようです。私のUserControlバインディングが機能しないのはなぜですか?

問題は、私がUserControl(BoxPanel)に値を渡しているが、値が表示されないということです。青のボックスはテキストなしで表示されます。

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" 
     xmlns:l="clr-namespace:WpfApplication1" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <l:BoxPanel Number="1" Text="Hi" /> 
    </Grid> 
</Window> 

BoxPanel.xaml

<UserControl x:Class="WpfApplication1.BoxPanel" 
     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" 
     Height="50" Width="90"> 
<Border Background="Blue"> 
    <StackPanel> 
     <TextBlock FontSize="20" HorizontalAlignment="Center" 
      Text="{Binding Number}" /> 
     <Label FontSize="10" HorizontalAlignment="Center" Foreground="White" 
      Content="{Binding Text}" /> 
    </StackPanel> 
</Border> 

BoxPanel.xaml.xs

public partial class BoxPanel : UserControl 
{ 
    public static readonly DependencyProperty NumberProperty = 
     DependencyProperty.Register("Number", typeof(decimal), typeof(BoxPanel)); 
    public static readonly DependencyProperty TextProperty = 
     DependencyProperty.Register("Text", typeof(string), typeof(BoxPanel)); 

    public BoxPanel() 
    { 
     InitializeComponent(); 
    } 

    public decimal Number 
    { 
     get { return (decimal)GetValue(NumberProperty); } 
     set { SetValue(NumberProperty, value); } 
    } 

    public string Text 
    { 
     get { return (string)base.GetValue(TextProperty); } 
     set { base.SetValue(TextProperty, value); } 
    } 
} 

答えて

0

バインディングパスは、デフォルトでDataContextをルートとしています。しかし、UserControlで定義されたプロパティにバインドしたいとします。だから何とかリダイレクトする必要があります。私は通常、ElementNameでそれをやります。

<UserControl x:Class="WpfApplication1.BoxPanel" 
     x:Name="BoxPanelRoot" 
     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" 
     Height="50" Width="90"> 
<Border Background="Blue"> 
    <StackPanel> 
     <TextBlock Text="{Binding Number, ElementName=BoxPanelRoot}" /> 
     <Label Content="{Binding Text, ElementName=BoxPanelRoot}" /> 
    </StackPanel> 
</Border> 

少し最初は奇数、このようなバインディングをリダイレクトするために多少厄介なようだが、それは、ユーザーコントロール内のDataContextを利用する他の方法よりもpreferrableあります。 DataContextをUserControlのルートに設定するなどしてDataContextをブロックすると、UserControlにデータを渡すための最良の方法が効果的にブロックされてしまいます。

UserControlでバインドするとき、UserControlにに渡されたデータに対して明示的にバインドしていない限り、DataContextだけを残します。

+0

ありがとうございました。私はStackOverflowのもう1つの例を見て、これをもう一度試してみようとしていました。 – David