簡體   English   中英

UserControl上的奇怪行為綁定DataContext和IsEnabled-Property

[英]Strange Behavior Binding DataContext & IsEnabled-Property on UserControl

我有一個綁定UserControl的DataContextIsEnabled屬性的奇怪行為。

在我的頁面中,我使用這樣的UserControl:

<httpsPort:HttpsPort DataContext="{Binding Path=Https}"
    IsEnabled="{Binding CurrentServiceState, Converter={StaticResource ServiceStateIsConfigableConverter}}" />

和這樣的按鈕:

<Button Content="start service"
    IsEnabled="{Binding CurrentServiceState, Converter={StaticResource ServiceStateIsConfigableConverter}}"
    Command="{Binding CmdConfigureService}" [...] />

說明:

轉換器將currentServiceState-Enum轉換為bool。 我的按鈕的行為符合我的預期(啟用/禁用)。

問題:我的按鈕已正確啟用/禁用,但我的usercontrol中的控件卻沒有。

DataContext(HTTPS)實際上不是null:

private HttpsPortViewModel _https;
    public HttpsPortViewModel Https
    {
        get
        {
            if (_https == null)
            {
                _https = new HttpsPortViewModel();
            }
            return _https;
        }
        set
        {
            _https = value;
            NotifyPropertyChanged(() => Https);
        }
    }

我試圖在我的UserControls綁定上使用FallbackValue = False,但是UserControl甚至被禁用...

有人可以解釋這些行為嗎? 非常感謝。

更新:

我的解決方法:

<Grid IsEnabled="{Binding CurrentServiceState, Converter={StaticResource ServiceStateIsConfigableConverter}}">
    <httpsPort:HttpsPort DataContext="{Binding Path=Https}" />
</Grid>

您不應該綁定自己的DataContext 任何綁定操作都使用DataContext ,因此綁定DataContext是循環操作。 即使這行得通,也不能保證以什么順序創建綁定,所以可以在將DataContext綁定到其新值之前綁定IsEnabled屬性。

相反,您應該指定屬性的完整路徑。 例如:

<httpsPort:HttpsPort IsEnabled="{Binding Https.CurrentServiceState, Converter={StaticResource ServiceStateIsConfigableConverter}}" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM