これを行うための最善の方法は、データモデルで同じバックエンドフィールドにテキストブロックやチェックボックスの両方に結合し、その後、コードコンバータを使用することです。
ここは簡単な例です。
を使用すると、1つのブールプロパティで次のような単純なビューモデルを持っていると言う:ここでは
class SimpleViewModel: INotifyPropertyChanged
{
private bool _checked;
// The property to bind to
public bool Checked
{
get { return _checked; }
set { _checked = value; OnPropertyChanged("Checked"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
は、テキストブロックやテキストフィールドを持つシンプルなページが同じバックエンドフィールドにバインド両方のこともあります。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:SimpleViewModel x:Key="simpleViewModel" />
<local:BoolToStringConverter x:Key="boolToStringConverter" />
</Window.Resources>
<Grid DataContext="{StaticResource simpleViewModel}">
<StackPanel>
<TextBlock Text="{Binding Checked, Converter={StaticResource boolToStringConverter}}" />
<CheckBox Content="something" IsChecked="{Binding Checked}" />
</StackPanel>
</Grid>
</Window>
ここで、テキストブロックバインディングステートメントにconverterステートメントが含まれていることに注目してください。 Text="{Binding Checked, Converter={StaticResource boolToStringConverter}}"
ここのコンバータは非常に簡単です。それが真であれば値をチェックし、そうでなければNOを返します。
public class BoolToStringConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null) return null;
if ((bool)value == true)
return "YES";
else
return "NO";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// this scenario is not needed since the text block is read only
throw new NotImplementedException();
}
}