對轉換器和代碼隱藏使用複雜的多重綁定不僅會使您的代碼更難調試,而且更難以測試。在我看來,最好將每組單選按鈕(標誌)表示爲視圖模型。當任何單選按鈕被選中/取消選中時,評估您的值。
的RadioButtonGroup
public class RadioButtonGroup : ViewModel {
public RadioButtonGroup(string groupName, int count, Action<bool[]> whenAnyChanaged = null) {
RadioButtons = Enumerable.Range(0, count).Select(_ => {
var button = new RadioButton { GroupName = groupName };
button.PropertyChanged += (s, e) => {
if (e.PropertyName == "IsChecked")
whenAnyChanaged(Flags);
};
return button;
}).ToList();
}
public List<RadioButton> RadioButtons { get; private set; }
public bool[] Flags { get { return RadioButtons.Select(rb => rb.IsChecked).ToArray(); } }
}
單選按鈕
public class RadioButton : ViewModel {
private bool isChecked;
public bool IsChecked {
get { return isChecked; }
set { SetProperty(ref this.isChecked, value); }
}
public string GroupName { get; set; }
}
MainViewModel
public class MainViewModel : ViewModel {
public MainViewModel() {
GroupA = new RadioButtonGroup("A", 10, flags => GroupToggle(flags, GroupB.Flags));
GroupB = new RadioButtonGroup("B", 10, flags => GroupToggle(GroupA.Flags, flags));
}
public RadioButtonGroup GroupA { get; private set; }
public RadioButtonGroup GroupB { get; private set; }
void GroupToggle(bool[] groupA, bool[] groupB) {
MyValue = Evaluate(groupA, groupB);
}
}
查看
<Window x:Class="WpfLab.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="{Binding Title}" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="RadioButton">
<RadioButton IsChecked="{Binding IsChecked, Mode=OneWayToSource}" GroupName="{Binding GroupName}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<ListBox Grid.Row="0" ItemsSource="{Binding GroupA.RadioButtons}" ItemTemplate="{StaticResource ResourceKey=RadioButton}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
<ListBox Grid.Row="1" ItemsSource="{Binding GroupB.RadioButtons}" ItemTemplate="{StaticResource ResourceKey=RadioButton}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</Grid>
來源
2012-09-22 10:42:17
Per
「使用一個大的多重綁定」,我不太明白。你有兩個radioButton組。您可以從group1中選擇一個項目,並且您可以從group2中選擇一個項目。我不明白'有新的正確價值'。 –
@ChrisDD:「大型多重綁定」將一次綁定「vm.Value」和全部六個單選按鈕。六個單選按鈕可以有一個初始狀態,例如'(1,0,0,1,0,0)'。現在,讓我們說有人點擊第二組中的第二個單選按鈕,所以我的多轉換器可以用'(1,0,0,0,1,0)'調用。我該如何確定第一組或第二組是否正確,即應返回第一枚枚舉值還是第二枚枚舉值?據我所知,這並不方便。 –
爲什麼你不使用單個綁定每個RadioButton?也使用轉換器和命令參數。例如:IsChecked = {綁定VMEnum,轉換器= {StaticResource toEnum},ConverterParameter = {YourEnum:FirstButtonChecked}}。你需要實現雙向轉換器。 無論哪種方式IsChecked = VMEnum ==(CommandParameter as Enum)[單向] –