WPF绑定到数据上下文和依赖项属性

时间:2018-08-30 07:32:31

标签: wpf data-binding dependency-properties

是否可以绑定到两个元素?

我有一个数据结构,可以在datacontext中绑定到它。 而且我想绑定到用户控件本身的依赖项属性。我可以吗?

对AddValue的绑定有效,但是对Num的出价(我用ElementName和RelativeSource进行了很多尝试)不起作用。

<TextBlock>
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource MultiValueConverter}">
            <Binding Path="AddValue"/>  // item from the datacontext given in the code
            <Binding Path="Num" />      // the dependency property 
         </MultiBinding>
     </TextBlock.Text>
</TextBlock>


public partial class MyUC: UserControl
{ 
  ....

  public int Num
  {
    get { return (int)GetValue(NumProperty); }
    set { SetValue(NumProperty, value); } 
  }

  public static readonly DependencyProperty AgeProperty = 
    DependencyProperty.Register("Num", typeof(int), typeof(MyUC));
}


public class MultiValueConverter: List<IValueConverter>, IValueConverter
{
       public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
       return  value + Num; 
     }
}

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

0 个答案:

没有答案