WPFに次のサンプルコードがあります。 xamlと対応するC#コードをウィンドウ内に配置するとうまくいきますが、ユーザーコントロールを使用しているときにはデータバインディングが機能しません。どうして?ここユーザーコントロールのデータバインドが機能しない(WPF)
コードがある:
ユーザ制御XAML:
<UserControl x:Class="TestWpf.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:ec="clr-namespace:TestWpf"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid x:Name="MainGrid" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<WrapPanel HorizontalAlignment="Right" VerticalAlignment="Stretch" Grid.Row="0" >
<Button Content="Edit" HorizontalAlignment="Right" Name="editButton1" VerticalAlignment="Stretch" Click="button1_Click" />
</WrapPanel>
<Grid x:Name="patientDataGrid" Margin="10,10,10,10" Grid.Row="1">
<Grid.Resources>
<Style TargetType="TextBox" >
<Setter Property="IsEnabled" Value="{Binding Path=IsEditing, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ec:UserControl1}}}" />
</Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBox x:Name="textBox1" Grid.Column="0" Text="!234" />
<TextBox x:Name="textBox2" Grid.Column="1" />
</Grid>
</Grid>
</UserControl>
ユーザ制御C#コード:
public partial class UserControl1 : UserControl
{
public static readonly DependencyProperty IsEditingProperty = DependencyProperty.Register(
"IsEditing", typeof(Boolean), typeof(MainWindow), new PropertyMetadata(false));
public Boolean IsEditing
{
get { return (Boolean)GetValue(IsEditingProperty); }
set { SetValue(IsEditingProperty, value); }
}
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
IsEditing = !IsEditing;
}
}
MainWindowsのXAML:
<Window x:Class="TestWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ec="clr-namespace:TestWpf"
Title="MainWindow" Height="200" Width="525">
<ec:UserControl1 x:Name="c" />
</Window>
私がいることがわかりもし私がすべてのC#とxamlコードをユーザーコントロールからMainWindowsに渡すと、バインディングは問題なく動作します。
コードに問題がありますか?
のために登録する必要があります。私は、この質問で尋ねた拘束力のある問題を見つけるためのテストプロジェクトを書いています:http://stackoverflow.com/questions/6647460/problem-in-wpf-binding – mans