2016-09-21 28 views
-1

我有一些XAML看起來(修剪)這樣的,有一個按鈕搭售其IsEnabled屬性的子屬性:啓用的子屬性變化WPF按鈕

<Grid DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}"> 
... 
    <Button x:Name="continueButton" Content="Continue" IsEnabled="{Binding CurrentQuestion.AnswerSelected, Mode=OneWay}" Click="continueButton_Click"/> 
... 

CurrentQuestion是拉從當前的屬性集合:

public Question CurrentQuestion { 
     get 
     { 
      return Questions[QuestionNo]; 
     } 
     set 
     { 
      Questions[QuestionNo] = value; 
     } 
} 

AnswerSelected檢查是否有任何Answer S的作爲選擇標記。

public bool AnswerSelected 
{ 
     get 
     { 
      return Answers.Any(a => a.Selected); 
     } 
} 

Selected屬性本身是通過單選按鈕設置綁定到可能的答案。因此,用戶應該能夠在選擇答案後繼續。

Answers集合更改監控,並從INotifyPropertyChanged調用OnPropertyChanged()方法爲AnswerSelected布爾屬性,像這樣:

public Answer[] Answers 
{ 
     get 
     { 
      return _answers; 
     } 
     set 
     { 
      _answers = value; 
      OnPropertyChanged("Answers"); 
      OnPropertyChanged("AnswerSelected"); 
     } 
} 

成功綁定設置按鈕,殘疾人開始的,但沒有改變單選按鈕然後重新啓用按鈕。我試圖移動AnswerSelected是一個屬於CurrentQuestion同一級別的財產,但這也不起作用。

我錯過了什麼讓這個按鈕重新啓用?另外,是否有更好的方法來完成同樣的事情?

編輯:

這是單選按鈕設定的代碼。

<Grid DataContext="{Binding CurrentQuestion, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"> 
     <ItemsControl ItemsSource="{Binding Answers}"> 
      <ItemsControl.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal"> 
         <RadioButton GroupName="AnswerGroup" IsChecked="{Binding Selected}"> 
          <TextBlock Text="{Binding Text}" /> 
         </RadioButton> 
        </StackPanel> 
       </DataTemplate> 
      </ItemsControl.ItemTemplate> 
     </ItemsControl> 
    </Grid> 

所以它看起來像這樣:

CurrentAnswer (Questions[QuestionNo]) 
    AnswerSelected (Answers.Any(a => a.Selected)) 

編輯2:

我想我的問題,有效的,是這樣的:綁定屬性是一個計算的屬性,但該計算使用數組元素的子屬性。因此,如何在子屬性更改時發出通知,該通知本身位於定義每個數組元素的不同類中?

+0

嘗試觸發'OnPropertyChanged(「CurrentQuestion.AnswerSelected」 );'在你的視圖模型 – NtFreX

+1

也許你應該添加'OnPropertyChanged(「CurrentQuestion」);'somethere。或者更好地使用Button.Command屬性而不是IsEnabled + Click事件。 – ASh

+0

我總是在我的viewmodels寫封裝,而不是使用neasted綁定。它更容易和更好在我看來 – NtFreX

回答

0

我最終需要做的是,以受到this question影響的方式,從Question類別訂閱每個AnswerPropertyChanged事件。

void SubscribeToSelect(Answer item) 
{ 
    item.PropertyChanged += (s, e) => this.AnswerSelected = e.PropertyName == "Selected" && item.Selected ? true : this.AnswerSelected; 
} 

當該開除,我更新了Question.AnswerSelected財產,被炒得上的更新,這反過來又更新了綁定按鈕:

private bool _answerSelected; 
public bool AnswerSelected 
{ 
    get 
    { 
     return _answerSelected; 
    } 
    set 
    { 
     _answerSelected = value; 
     OnPropertyChanged("AnswerSelected"); 
    } 
}