DataTemplate中におけるUserControlのBinding
問題はListViewなどのItemSourceからDataTemplateでUserControlを呼び出したとき、その中のBindingがうまくいかないことです。
作成したUserControlは以下の通りで、
MyUserControl1.cs
namespace EditableTextBox
{
public sealed partial class MyUserControl1 : UserControl
{
public string Text
{
get
{
return (string)GetValue(TextProperty);
}
set
{
SetValue(TextProperty, value);
}
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyUserControl1), new PropertyMetadata(null));
public MyUserControl1()
{
this.InitializeComponent();
this.DataContext = this;
}
private void TextBlock_Tapped(object sender, TappedRoutedEventArgs e)
{
Block.Visibility = Visibility.Collapsed;
Box.Visibility = Visibility.Visible;
}
private void Box_LostFocus(object sender, RoutedEventArgs e)
{
Block.Visibility = Visibility.Visible;
Box.Visibility = Visibility.Collapsed;
}
}
}
MyUsercontrol1.xaml
<UserControl
x:Class="EditableTextBox.MyUserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:EditableTextBox"
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>
<TextBlock Visibility ="Visible" Name="Block" Text="{Binding Text, Mode=TwoWay}" Tapped="TextBlock_Tapped"/>
<TextBox Visibility="Collapsed" Name="Box" Text="{Binding Text, Mode=TwoWay}" LostFocus="Box_LostFocus"/>
</Grid>
そしてUserControlを呼び出すためのMainPage.xamlが以下の通りです。
MainPage.xaml.cs
namespace EditableTextBox
{
/// <summary>
/// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
test = "test";
test2 = new List<string>();
test2.Add("1");
test2.Add("2");
this.DataContext = this;
}
public string test { get; set; }
public List<string> test2 { get; set; }
}
}
MainPage.xaml
<Page
x:Class="EditableTextBox.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:EditableTextBox"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<local:MyUserControl1 Text="{x:Bind test,Mode=TwoWay}" HorizontalAlignment="Left" Margin="304,227,0,0" VerticalAlignment="Top" Width="568" Height="35"/>
<ListView ItemsSource="{x:Bind test2,Mode=TwoWay}" HorizontalAlignment="Left" Height="416" Margin="309,380,0,0" VerticalAlignment="Top" Width="617">
<ListView.ItemTemplate>
<DataTemplate x:DataType="x:String">
<local:MyUserControl1 Text="{Binding}"></local:MyUserControl1>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>