WPF-Property在XAML和UserControl自定义基类中设置顺序

时间:2016-07-03 16:24:02

标签: wpf xaml properties user-controls

问题在于属性初始化/设置。 UserControl中出现问题,它来自基类(其中定义了属性)。 UserControl包含一个文本框和基类中定义的一些业务逻辑。

setter中的VariableName属性调用方法,该方法使用来自同一基类的VariableType属性。

在XAML中首先定义VariableName时出现问题。我必须确保VariableType在VariableName之前获取值。

public Enums.Types VariableType
{
    get
    {
        return _variableType;
    }
    set
    {
        _variableType = value;
        if (!string.IsNullOrEmpty(_variableName) && Type == null)
            SetType();
    }
}
public string VariableName
{
    get { return _variableName; }
    set
    {
        _variableName = value;
        if (!string.IsNullOrEmpty(_variableName) && Type == null)
            SetType();
    }
}
private void SetType()
{
    if (Vars == null)
        PopulateVars();
    if (VariableType != Enums.Types.Default)
    {
        Type = Types.SetOveridenType(VariableType);
    }

}

And XAML:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestShell"
xmlns:Controls="clr-namespace:Controls.Controls;assembly=Controls" x:Class="TestShell.MainWindow"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
    <Controls:Numeric HorizontalAlignment="Left" Margin="186,37,0,0" VerticalAlignment="Top" Height="40" Width="111" VariableName="SomeName" VariableType="Int16"/>
</Grid>

1 个答案:

答案 0 :(得分:0)

  

我必须确保VariableType在VariableName之前获取值。

我认为您认为必须始终先设置该值。在某些情况下,如果值无效,您希望停止此操作。我可以建议在VariableName的设置实现中添加额外的检查吗?

也就是说,您不必立即执行设置,而是检查是否已设置VariableType。如果是这样,请设置VariableName,然后执行您的操作。否则,价值保持不变。我注意到当发生这种情况并且数据绑定到TextBox时,TextBox会以红色标出,直到设置了有效值。

这是您的代码应该是什么样子:

public string VariableName
{
    get { return _variableName; }
    set
    {
        //I put both conditions here because I forgot, which is 
        //the correct way for checking if an enum value is null,
        //though, my gut's telling me it's the first you'll want 
        //to stick with.
        if (VariableType == default(Enums.Types) || VariableType == null)
            return;
        //VariableType is definitely not null so it's okay to do stuff.
        _variableName = value;
    }
}

Tbh,您的代码相对难以理解,因为您首先在UserControl上设置类型,然后在VariableTypeVariableName更改时尝试再次设置它,但仅当值为空。

VariableType最初必须为空的任何特殊原因?我总是确保我的枚举有一个默认的枚举值,所以我永远不必检查该值是否为空,只是它是默认类型(你在SetType中做的),但只检查它是否& #39; s null)。

在不了解业务逻辑的情况下,很难提供任何进一步的建议。