2015-12-29 25 views
0

我正在使用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(); 
     } 
    } 
} 

回答

0

绑定到性能,只要它们是dependncy性能,是简单的解决方案,以了解发生了一些变化。
如果您想超越边界,您可以创建依赖属性侦听器,并且在更改特定属性时发送一些消息,例如使用MVVM Light。然后根据更改的DP,在需要更新某些数据的位置捕获此消息。无论如何,我不会劝你采取这样一个复杂的步骤。

顺便说一句,你设置绑定到按钮,因为按钮是UI元素,那么作为结果转换器将被调用一次,永远不会再次记住。
创建另一个文件夹,将其命名为转换器,并将它们全部归类为IValueConverter或IMultiValueConverter。这样的一个步骤可以让你获得明显的分离,并且不会让你的代码隐藏文件中的代码不相关。

+0

我知道转换器被调用一次,永不再次,这是我正在寻求解决方案的问题。 – horns

相关问题