我使用直接绑定到控件的Binding
+IValueConverter
来生成使用控件上的多个属性计算的结果。每当控件上的属性发生变化时,有什么方法可以调用转换器?
我知道可以使用 IMultiValueConverter 绑定到我想要的属性,但这会占用代码中的大量空间并中断流程。
示例代码:
主窗口.xaml
<Window x:Class="BindingToFrameworkElement.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindingToFrameworkElement"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:ElementConverter x:Key="ElementConverter"/>
</Window.Resources>
<Grid>
<TextBlock Text="{Binding ElementName=B, Converter={StaticResource ElementConverter}}"/>
<Button Name="B" Click="Button_Click" Width="50" Height="20">Hello</Button>
</Grid>
</Window>
主窗口.xaml.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace BindingToFrameworkElement
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
B.Width += 20;
}
}
public class ElementConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
FrameworkElement element = value as FrameworkElement;
return element.ActualWidth + element.ActualHeight;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}