2012-04-16 51 views
0

我有一个奇怪的绑定行为DataContext & IsEnabled UserControl的属性。奇怪的行为在UserControl上绑定DataContext&IsEnabled-Property

在我的网页,我用这样的用户控件:

<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-枚举到转换布尔。我的按钮的行为如我所料(En/DisAbled)。

问题:我的按钮是正确的en /禁用,但我的用户控件中的控件不是。

DataContext的(HTTPS)实际上是不为空:

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

我曾尝试使用FallbackValue =我的用户控件绑定假,但随后用户控件甚至禁用...

任何人可以解释这些行为? 非常感谢。

更新:

我的解决方法:

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

你从来没有真正说过你的问题。请这样做。 – 2012-04-16 09:05:41

+0

嗨丹尼尔,问题是,用户控件不是像按钮一样被禁用/禁用。 – 2012-04-16 09:17:32

+0

我不认为绑定DataContext属性是个好主意。你为什么要为usercontrol做这件事?它似乎适用于没有它的按钮。 – 2012-04-16 09:28:52

回答

0

你不应该结合自己的DataContext。任何绑定操作使用DataContext,因此绑定您的DataContext是一个循环操作。即使这种方法奏效,也无法保证绑定创建的顺序,因此您的IsEnabled属性可能会在您的DataContext绑定到其新值之前绑定。

相反,您应该指定属性的完整路径。例如:

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

好吧,我明白绑定顺序的问题。主要想法是将一组控件外包为用户控件。这些groupbox用于两个(页面)ViewModels。这些ViewModel需要访问UserControlViewModel(获取端口和选定的证书),但(页面)视图模型应该能够禁用usercontrol(例如服务正在运行)。也许,我的“解决方案”不是最好的方法......注意CurrentServiceState不是https的属性,它是父视图模型(页面)的属性 – 2012-04-16 10:17:04

+0

然后,只需从每个PageViewModel公开UserControlViewModel。 DataContext保持指向一个PageViewModel,你可以绑定你的用户控件属性和完整路径,就像我的答案一样。 – GazTheDestroyer 2012-04-16 12:14:31