我们有一个应用程序,它使用简单的单向绑定与 GridView 来显示一些数据。好吧,现在我们需要允许用户更改一些数据,所以我一直在尝试让两种方式的数据绑定在 GridView 中工作。到目前为止,一切都正确显示,但在 GridView 中编辑单元格似乎什么也没做。我在搞砸什么?像这样的双向数据绑定甚至可能吗?我是否应该开始转换所有内容以使用不同的控件,比如 DataGrid?
我写了一个小测试应用程序来显示我的问题。如果你尝试一下,你会发现属性设置器在初始化后永远不会被调用。
xml:
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));
}
}