我使用以下代码在我的控制中使用类系统:
public class FlowProWorkingClass:DependencyObject
{
public TUnitSystemClass ProjectUnitSystem
{
get
{
return Classes.CurrentFlowProWorkingClass.GeneralOptions.listOfUnitSystems.Find(x => x.Id == Classes.CurrentFlowProWorkingClass.GeneralOptions.DefaultUnitSystemId);
}
set
{
throw new Exception("Project Unit System can not be setted here!");}
}
}
我将它绑定到我的控件,如下所示:
<WPFTextBoxUnitConverterControl:TextBoxUnitConvertor
x:Name="txtGasPhaseFlowCoefficient" UnitSystem="{Binding currentFlowProWorkingClass.ProjectUnitSystem, Mode=OneWay, Source={StaticResource CurrentFlowProWorkingClass}, UpdateSourceTrigger=PropertyChanged}"
Height="27" Margin="167,245,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="171"/>
此代码运行良好,目前正在获取单位系统。 现在需要控件,当它打开时,我修改了第一个类添加下面的代码来通知更改:
public class FlowProWorkingClass:DependencyObject
{
[JsonIgnore]
public static readonly DependencyProperty ProjectUnitSystemProperty =
DependencyProperty.Register(
"ProjectUnitSystem",
typeof(TUnitSystemClass),
typeof(FlowProWorkingClass),
new PropertyMetadata(ProjectUnitSystemOnChanged));
private static void ProjectUnitSystemOnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
public TUnitSystemClass ProjectUnitSystem
{
get
{
SetValue(ProjectUnitSystemProperty, Classes.CurrentFlowProWorkingClass.GeneralOptions.listOfUnitSystems.Find(x => x.Id == Classes.CurrentFlowProWorkingClass.GeneralOptions.DefaultUnitSystemId));
return (TUnitSystemClass) GetValue(ProjectUnitSystemProperty);
}
set
{
throw new Exception("Project Unit System can not be setted here!");
}
}
}
但是现在,控件根本没有绑定! 有什么问题? 注意:当我写下面的代码时,绑定被完全忽略!根本没有调用get方法!为什么呢?
public static DependencyProperty ProjectUnitSystemProperty =
DependencyProperty.Register(
"ProjectUnitSystem",
typeof(TUnitSystemClass),
typeof(FlowProWorkingClass),
new PropertyMetadata(ProjectUnitSystemOnChanged));
private static void ProjectUnitSystemOnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
public TUnitSystemClass ProjectUnitSystem
{
get
{
SetValue(ProjectUnitSystemProperty, Classes.CurrentFlowProWorkingClass.GeneralOptions.listOfUnitSystems.Find(x => x.Id == Classes.CurrentFlowProWorkingClass.GeneralOptions.DefaultUnitSystemId));
return (TUnitSystemClass) GetValue(ProjectUnitSystemProperty);
}
set
{
throw new Exception("Project Unit System can not be setted here!");
}
}
答案 0 :(得分:1)
SetValue
设置所谓的依赖项属性的本地值,它替换任何先前分配的(单向)绑定。
所以你的属性getter有效地删除了Binding。不得致电SetValue
。
get
{
SetValue(ProjectUnitSystemProperty, ...); // remove this line
return (TUnitSystemClass)GetValue(ProjectUnitSystemProperty);
}
任何读/写依赖项属性的CLR包装器必须完全如下所示:
public PropertyType PropertyName
{
get { return (PropertyType)GetValue(PropertyNameProperty); }
set { SetValue(PropertyNameProperty, value);
}
对于只读依赖项属性,请查看MSDN上的Read-Only Dependency Properties文章。