Silverlight自定义控件中转换器绑定问题

时间:2010-02-09 04:57:52

标签: silverlight binding controls converter

我在这里得到了一些xaml,我试图做的只是在一个矩形的宽度上绑定一个属性调用Property(不是真名),并用转换器名称Conv转换这个属性的值,它的工作完美使用{TemplateBinding Property}或DataContext = {TemplateBinding Property}或使用相对源(如代码示例中所示)。

我的问题是converterParameter也应该是绑定属性,但我无法绑定converterParameter中的任何属性。所以样本中的30应该是{Binding Path = SecondProperty}。如果有人遇到这个问题,或者如果有人有其他办法在自定义控件中绑定东西,非常感谢;)

<ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:controls="clr-namespace:RatingControl">
  <Style TargetType="controls:Ctr">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="controls:Ctr">
          <Grid>
            <Grid.Resources>
              <controls:Converter x:Name="Conv" />
            </Grid.Resources>
            <Rectangle x:Name="rect" Width="{Binding Path=Property, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource Conv}, ConverterParameter=30}" Height="20" />

4 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

您可以向Converter类添加属性并绑定到该属性。

答案 2 :(得分:0)

您无法绑定到Binding对象的属性,因为它实际上不是DependencyProperty绑定不是DependencyObject。这是可以理解的,你能想象管理依赖树的复杂性以及绑定中递归或循环绑定的可能性。

但是你可以使用Specialized转换器来完成任务: -

public class MySpecialConverter: IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Ctr obj = (Ctr)value;
        var val = obj.Property;
        var param = obj.SecondProperty;
        // Do your intended code with val and param here.
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException("This converter only works for one way binding");
    }
}

现在您的Xaml看起来像: -

<Rectangle x:Name="rect" Height="20"
  Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource Conv}" />

答案 3 :(得分:0)

这是一个非常好的解决方案,但是它没有工作bcs我的第一个属性必须是bind(twoWay)因为如果我对它有任何改变,转换器必须再次转换值,所以我得到结果并显示真实结果。< / p>