【问题标题】:Problem with binding in converter in silverlight custom controlSilverlight自定义控件中的转换器绑定问题
【发布时间】:2011-01-14 16:07:57
【问题描述】:

我在这里得到了一些 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" />

【问题讨论】:

  • 欢迎来到 SO,请花几分钟时间阅读常见问题解答和 Markdown 文档(编辑问题时右侧空白处提供了有用的概要)。

标签: silverlight binding controls converter


【解决方案1】:
【解决方案2】:

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

【讨论】:

  • 这是一个有趣的想法。如果它有效,你真的应该充实这个答案。转换器需要是FrameworkElement,属性需要是依赖属性。是否可以在这样的资源字典中使用RelativeSource 绑定仍有待观察。我想不出为什么不。
  • 这不是真的。转换器不需要是框架元素,只需一个 CLR 类。
【解决方案3】:

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

但是,您可以使用专用转换器来完成任务:-

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}" />

【讨论】:

    【解决方案4】:

    这是一个非常好的解决方案,但它不起作用 bcs 我的第一个属性必须绑定(双向),因为如果我对其进行任何更改,转换器必须再次转换该值,以便我得到结果并显示真实结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      相关资源
      最近更新 更多