WPF MVVM - 如何绑定自定义控件 - > ToggleButton.IsChecked to View-> TextBox.Text [英] WPF MVVM - How to Bind Custom Control->ToggleButton.IsChecked to View->TextBox.Text
本文介绍了WPF MVVM - 如何绑定自定义控件 - > ToggleButton.IsChecked to View-> TextBox.Text的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I am moving over from WinForms to WPF and trying to implement the MVVM pattern for a touchscreen application. I created several custom controls inside a WPF Control Library (dll), and I can bring these controls into the View with no issue. However, I am getting stuck on a purely academic scenario where I want a TextBox inside the View to display my custom control's ToggleButton.IsChecked property as "Checked" and "Unchecked" respectively.
To sum up, I need to know the proper way to expose properties of a control that is inside a custom user control. Then when the exposed property changes update some other control with custom data based on the property that changed.
推荐答案
你可以使用所谓的价值转换器实现这一点。
BoolToCheckedConverter.cs:
You can use a so-called value converter for achieving this.
BoolToCheckedConverter.cs:
using System;
using System.Windows.Data;
namespace WpfApplicationToggleButtonTest
{
class BoolToCheckedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if((bool)value)
{
return "Checked";
}
else
{
return "Unchecked";
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
MainWindow.xaml:
MainWindow.xaml:
<Window x:Class="WpfApplicationToggleButtonTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplicationToggleButtonTest"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:BoolToCheckedConverter x:Key="b2c"></local:BoolToCheckedConverter>
</Window.Resources>
<Grid>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<ToggleButton x:Name="toggleButton" Width="75" Height="25" Margin="10" Content="Click me"></ToggleButton>
<TextBlock Text="{Binding ElementName=toggleButton,Path=IsChecked,Converter={StaticResource b2c}}" VerticalAlignment="Center"></TextBlock>
</StackPanel>
</Grid>
</Window>
这篇关于WPF MVVM - 如何绑定自定义控件 - > ToggleButton.IsChecked to View-> TextBox.Text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文