我正在使用Binding
+ IValueConverter
直接绑定到控件以生成使用控件上的多个属性计算的结果。只要控件上的属性发生变化,是否有办法让转换器进行调用?当属性更改时,绑定到控件不会更新
我知道可以使用IMultiValueConverter来绑定到我想要的属性,但是这占用了代码中的大量空间并打破了流程。
例如代码:
MainWindow.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>
MainWindow.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();
}
}
}
我知道转换器被调用一次,永不再次,这是我正在寻求解决方案的问题。 – horns