通过代码从XAML获取绑定的ElementName

时间:2016-08-01 04:08:24

标签: c# wpf xaml

这是我项目中的XAML片段:

 <TextBox x:Name="txt_Time1" LostFocus="TextBox_LoseFocus">
    <TextBox.Text>
    <Binding Converter="{StaticResource timezoneconverter}" 
     ElementName="cmb_TZ1" Path="SelectedValue"/>
    </TextBox.Text>
 </TextBox>

在我的代码中:

      private void TextBox_LoseFocus(object Sender, EventArgs e)
         {
         var txtBox = Sender as TextBox;

我的问题是:是否可以通过代码获取此TextBox的ElementName?

编辑:添加到此问题以使其四舍五入。
如何在MultiBinding场景中完成?

 <TextBox x:Name="txt_Time1" LostFocus="TextBox_LostFocus" >
          <TextBox.Text>
              <MultiBinding Converter="{StaticResource timezoneconverter}">
              <Binding ElementName="cmb_TZ1" Path="SelectedValue"/>
              <Binding RelativeSource="{RelativeSource Self}" Path="Text"/>
              </MultiBinding>
          </TextBox.Text>
      </TextBox>

4 个答案:

答案 0 :(得分:2)

BindingOperations.GetBinding(...)将为您提供BindingElementName属于Binding类的属性。

答案 1 :(得分:1)

BindingExpression bindingExpression = textBox1.GetBindingExpression(TextBox.TextProperty); 绑定parentBinding = bindingExpression.ParentBinding;

答案 2 :(得分:1)

你可以这样做,

  private void txt_Time_LostFocus(object sender, RoutedEventArgs e)
        {
            var txtBox = sender as TextBox;
            Binding myBinding = BindingOperations.GetBinding(txt_Time, TextBox.TextProperty);
            var elementName = myBinding.ElementName;
        }

答案 3 :(得分:0)

用于在普通绑定中检索元素名称:

  BindingExpression bindingExpression =   
  txtBox.GetBindingExpression(TextBox.TextProperty);
  Binding parentBinding = bindingExpression.ParentBinding;
  String elementName = parentBinding.ElementName;

在多重绑定场景中:

 MultiBindingExpression multiBindingExpression = BindingOperations.GetMultiBindingExpression(txtBox, TextBox.TextProperty);
 Binding parentBinding = ((BindingExpression)multiBindingExpression.BindingExpressions[0]).ParentBinding;
 String elementName = parentBinding.ElementName;