問題在於屬性初始化/設置。在從基類派生的UserControl中(其中是屬性定義的)會發生問題。 UserControl由一個文本框和一些在基類中定義的業務邏輯組成。XAML和UserControl自定義基類中的WPF-屬性設置順序
setter中的VariableName屬性調用使用同一基類的VariableType屬性的方法。
當在XAML中首先定義變量名稱時發生問題。我必須確保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>
嗨,謝謝你的回答。就像這樣。 VariableType是不可空的枚舉,並且值始終是默認值。 另一方面,類型是類型:)。 控件用戶可以在設計時通過enum更改變量類型,或者在運行時動態設置值。 問題是當變量名被設置在枚舉變量類型之前,因爲那麼我有錯誤的默認值,而不是例如Int32。 –
無論如何,我通過設置初始化控制的方法來解決這個問題。所以我確定所有道具都已初始化。 –