Joe*_*Joe 2 data-binding wpf xaml gridview two-way-binding
我们有一个应用程序使用简单的单向绑定与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>
Run Code Online (Sandbox Code Playgroud)
这是相应的代码:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
使用依赖项属性时,不会通过绑定调用Setter,而是直接更改值(使用SetValue或类似的东西).
尝试添加PropertyChangedCallback,并在其中设置断点以查看是否从GridView更改了值.
public static readonly DependencyProperty BoolProperty =
DependencyProperty.Register("Bool", typeof(bool), typeof(TestRow), new UIPropertyMetadata(false, OnBoolChanged));
private static void OnBoolChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
//this method will be called everytime Bool changes value
}
Run Code Online (Sandbox Code Playgroud)