Để có thể binding được cho một group các RadioButton chúng ta cần một số thủ thuật, giới hạn trong bài này tôi sẽ chia sẽ một kỹ thuật - dùng Converter, Converter tôi đã hướng dẫn ở bài trước, các bạn có thể xem để biết thêm...
Chúng ta tạo một Enum thể hiện cho các tùy chọn của một groupRadio và class Model
[code language="csharp"]
public enum StylesChecking
{
Is,
NotIs,
Container
}
public class Model: INotifyPropertyChanged
{
StylesChecking _currentOption;
public StylesChecking CurrentOption
{
get { return _currentOption; }
internal set
{
this._currentOption = value;
OnPropertyChanged(); //Xem thêm về Databinding
}
}
#region Event
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
[/code]
Tiếp theo cần implement một class Converter
[code language="csharp"]
public class EnumMatchToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return false;
string checkValue = value.ToString();
string targetValue = parameter.ToString();
// Nếu giá trị param trùng với giá trị hiện tại của thuộc tính trong Model => true
return checkValue.Equals(targetValue,
StringComparison.InvariantCultureIgnoreCase);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return null;
bool useValue = (bool)value;
string targetValue = parameter.ToString();
if (useValue)
{
// Nếu trạng thái hiện tại của radioBtn này là true
// Parse từ string của param sang Enum
return StylesChecking.Parse(targetType, targetValue);
}
return null;
}
}
[/code]
Cuối cùng ta dùng nó như sau
[code language="xml"]
<[RootElementName].Resources>
<[localNamespace]:EnumMatchToBooleanConverter x:Key="enumConverter" />
</[RootElementName].Resources>
<!-- ... ->
<WrapPanel>
<RadioButton GroupName="Options1" Content="Is" HorizontalAlignment="Right"
IsChecked="{Binding Path=CurrentOption, Mode=TwoWay,
Converter={StaticResource enumConverter},
ConverterParameter=Is}"
Height="16" Margin="0,0,4,0"/>
<RadioButton GroupName="Options1" Content="Not is" HorizontalAlignment="Right"
IsChecked="{Binding Path=CurrentOption, Mode=TwoWay,
Converter={StaticResource enumConverter},
ConverterParameter=NotIs}"
Height="16" Margin="0,0,4,0"/>
<RadioButton GroupName="Options1" Margin="0,0,4,0"
IsChecked="{Binding Path=CurrentOption, Mode=TwoWay,
Converter={StaticResource enumConverter},
ConverterParameter=Container}"
Content="Container" HorizontalAlignment="Right" Height="16"/>
</WrapPanel>
[/code]
Lưu ý mỗi RadioButton có một ConverterParameter riêng và nó phải maping với Enum
Chúc các bạn thành công!
Phạm Tuân
No comments:
Post a Comment