GridView との単純な一方向バインディングを使用してデータを表示するアプリがあります。さて、ユーザーがそのデータの一部を変更できるようにする必要があるため、GridView で双方向のデータ バインディングを機能させようとしました。これまでのところ、すべてが正しく表示されていますが、GridView でセルを編集しても何も起こらないようです。私は何を台無しにしていますか?このような双方向のデータバインディングは可能ですか? おそらく DataGrid のように、別のコントロールを使用するようにすべてを変換する必要がありますか?
私の問題を示す小さなテストアプリを作成しました。試してみると、初期化後にプロパティ セッターが呼び出されないことがわかります。
Xaml:
Title="Window1" Height="300" Width="300">
<Grid>
<ListView Name="TestList">
<ListView.View>
<GridView>
<GridViewColumn Header="Strings">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=String, Mode=TwoWay}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Bools">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=Bool, Mode=TwoWay}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
そして、対応するコードは次のとおりです。
using System.Collections.Generic;
using System.Windows;
namespace GridViewTextbox
{
public partial class Window1 : Window
{
private List<TestRow> _rows = new List<TestRow>();
public Window1()
{
InitializeComponent();
_rows.Add(new TestRow("a", false));
_rows.Add(new TestRow("b", true));
_rows.Add(new TestRow("c", false));
TestList.ItemsSource = _rows;
TestList.DataContext = _rows;
}
}
public class TestRow : System.Windows.DependencyObject
{
public TestRow(string s, bool b)
{
String = s;
Bool = b;
}
public string String
{
get { return (string)GetValue(StringProperty); }
set { SetValue(StringProperty, value); }
}
// Using a DependencyProperty as the backing store for String. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StringProperty =
DependencyProperty.Register("String", typeof(string), typeof(TestRow), new UIPropertyMetadata(""));
public bool Bool
{
get { return (bool)GetValue(BoolProperty); }
set { SetValue(BoolProperty, value); }
}
// Using a DependencyProperty as the backing store for Bool. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BoolProperty =
DependencyProperty.Register("Bool", typeof(bool), typeof(TestRow), new UIPropertyMetadata(false));
}
}