简体   繁体   中英

Get ElementName of Binding from XAML through code

This is an XAML snippet from my project:

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

In my code here:

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

My Question is: Is it possible to get the ElementName of this TextBox through code?

EDIT: To add to this question in order to make it rounded.
How can this be done in a MultiBinding scenario?

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

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

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

You can do this,

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

For retrieving the Element Name in plain Binding :

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

In a Multi Binding Scenario :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM