2016-07-03 56 views
1

問題在於屬性初始化/設置。在從基類派生的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> 

回答

0

I must ensure that VariableType gets value before VariableName.

I think you're assuming the value must always be set first. There are some cases in which you want to stop this operation if value is invalid. Might I suggest adding an additional check in set implementation of VariableName

也就是說,不是立即執行設置,而是檢查是否已設置VariableType。如果是這樣,設置VariableName,然後做你的東西。否則,價值保持不變。我注意到,當發生這種情況並且數據綁定到文本框時,文本框變爲紅色,直到設置了有效值。

這裏是你的代碼應該是什麼樣子:

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,你的代碼是相對難以遵循你第一次在用戶控件的類型,然後再次嘗試時,無論是VariableTypeVariableName設置更改,但僅限於該值爲空。

VariableType必須初始爲空的任何特定原因?我總是確保我的枚舉具有默認枚舉值,所以我永遠不必檢查值是否爲空,就像它是默認類型(在SetType中執行的操作,但僅在檢查它是否爲空之後)。

不知道業務邏輯,很難提供任何進一步的建議。

+0

嗨,謝謝你的回答。就像這樣。 VariableType是不可空的枚舉,並且值始終是默認值。 另一方面,類型是類型:)。 控件用戶可以在設計時通過enum更改變量類型,或者在運行時動態設置值。 問題是當變量名被設置在枚舉變量類型之前,因爲那麼我有錯誤的默認值,而不是例如Int32。 –

+0

無論如何,我通過設置初始化控制的方法來解決這個問題。所以我確定所有道具都已初始化。 –

相關問題