我在这里使用依赖项对象,之前并没有对它们做太多的事情,但它们看起来非常有用。
基本上我已经在ListView中使用这些对象进行编辑。但是,我必须将这些更改写回SQL。我的问题是,有没有办法记录数据是否已被修改,因为每次有人查看数据时我都不想写回SQL。目前我有这个:
public class KPI : DependencyObject
{
public static readonly DependencyProperty DepartmentProperty = DependencyProperty.Register("Department", typeof(string), typeof(KPI), new UIPropertyMetadata(null));
public string Department
{
get { return (string)GetValue(DepartmentProperty); }
set { SetValue(DepartmentProperty, value); }
}
public static readonly DependencyProperty KPINumberProperty = DependencyProperty.Register("KPINumberProperty", typeof(int), typeof(KPI), new UIPropertyMetadata(null));
public int KPINumber
{
get { return (int)GetValue(KPINumberProperty); }
set { SetValue(KPINumberProperty, value); }
}
}
我的想法是拥有类似的东西:
public static bool DataModified = false;
public static readonly DependencyProperty DepartmentProperty = DependencyProperty.Register("Department", typeof(string), typeof(KPI), new UIPropertyMetadata(null));
public string Department
{
get { return (string)GetValue(DepartmentProperty); }
set { SetValue(DepartmentProperty, value); DataModified = true; }
}
因此,每次编辑某些内容时,DataModified属性都将设置为TRUE,这是一种很好的方法吗?或者有人有更好的方法吗?
提前致谢。
SumGuy。
答案 0 :(得分:4)
如果您绑定到依赖项属性,这实际上将不起作用。 WPF绑定引擎实际上并不使用您的CLR“Department”属性,而是直接在依赖属性上使用“SetValue”。虽然有一个简单的解决方案。
UIPropertyMetadata有一个PropertyChangedCallback字段,每次更改属性值时都会触发该字段(从直接调用SetValue或通过包装SetValue调用的CLR属性)
以下是一个例子:
public static readonly DependencyProperty DepartmentProperty =
DependencyProperty.Register("Department",
typeof(string),
typeof(KPI),
new UIPropertyMetadata(null, DepartmentPropertyChanged));
private static void DepartmentPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
KPI me = d as KPI;
if (me == null) return;
// Talk to your Business/Data layers here
}
public string Department
{
get { return (string)GetValue(DepartmentProperty); }
set { SetValue(DepartmentProperty, value); }
}
DependencyObject(d)是属性所属的对象。在您的情况下,这将是KPI的一个实例。
供参考,这里是UIPropertyMetadata MSDN文档的链接:http://msdn.microsoft.com/en-us/library/system.windows.uipropertymetadata.aspx
答案 1 :(得分:1)
WPF绑定系统不必须调用Department
CLR属性,而是在更新依赖属性时直接调用SetValue
(在本例中为Department
)。这意味着,您的CLR包装器可能不会被调用,这反过来意味着您在set
块(Department
CLR属性)中编写的任何代码都不会被执行。
但不要担心,有解决方案。初始化DepartmentProperty
时,您可以将回调传递给UIPropertyMetadata
,每次更新依赖项属性时都会调用该回调。这意味着,你要实现这个:
public static readonly DependencyProperty DepartmentProperty = DependencyProperty.Register
(
"Department",
typeof(string),
typeof(KPI),
new UIPropertyMetadata(null, OnDepartmentChanged)
);
public string Department
{
get { return (string)GetValue(DepartmentProperty); }
set { SetValue(DepartmentProperty, value);}
}
static void OnDepartmentChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
(d as KPI).DataModified = true; //this is all you want!
}