我有一些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:
我想我的問題,有效的,是這樣的:綁定屬性是一個計算的屬性,但該計算使用數組元素的子屬性。因此,如何在子屬性更改時發出通知,該通知本身位於定義每個數組元素的不同類中?
嘗試觸發'OnPropertyChanged(「CurrentQuestion.AnswerSelected」 );'在你的視圖模型 – NtFreX
也許你應該添加'OnPropertyChanged(「CurrentQuestion」);'somethere。或者更好地使用Button.Command屬性而不是IsEnabled + Click事件。 – ASh
我總是在我的viewmodels寫封裝,而不是使用neasted綁定。它更容易和更好在我看來 – NtFreX