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

本文关键字:绑定 ElementName 获取 XAML 代码 | 更新日期: 2023-09-27 17:59:39

这是我的项目中的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?

编辑:添加到这个问题中,使其四舍五入。
在多绑定场景中如何做到这一点

 <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>

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

BindingOperations.GetBinding(...)将给您Binding,而ElementNameBinding类的属性。

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

,你可以做到这一点

  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;
        }

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

  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;