WPF binding to another property's binding in a style

后端 未结 2 1598
情歌与酒
情歌与酒 2021-01-15 08:43

I\'m not sure the best way to ask this question (sorry for the ambiguous question title), but essentially I\'d like to set the MaxLength property on a TextBox using a value

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-15 09:14

    Ok, after some more digging, I've figured this out to my satisfaction. I'm binding to RelativeSource Self and then parsing the binding expression on the Text property (since this is a TextFieldMaxLength converter, I am presuming I'm working against a TextBox.

    The styling up in the resource dictionary:

    
    

    The usage (basically showing nothing special needs to be done since it's all in the style):

    
    

    The Convert Method for the textFieldMaxLengthConverter:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      Control control = value as Control;
      BindingExpression be = control.GetBindingExpression(TextBox.TextProperty);
      if (be != null)
      {
        string boundPropertyName = be.ParentBinding.Path.Path;
        // .. boundPropertyName here is MyPropertyName.TheirPropertyname, do some parsing and return a value based on that
      }
    }
    

    (Obviously my actual implementation is a bit more complex/handles unexpected input/uses reflection as per my original question's statement).

    Anyway, thought I would post this solution in case anyone else tries to do something similar, or if there might be a better way to do this than I am using.

提交回复
热议问题