简体   繁体   English

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

[英]Get ElementName of Binding from XAML through code

This is an XAML snippet from my project: 这是我的项目中的XAML代码段:

 <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? 我的问题是:是否可以通过代码获取此TextBox的ElementName?

EDIT: To add to this question in order to make it rounded. 编辑:添加到此问题以使其四舍五入。
How can this be done in a MultiBinding scenario? 在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>

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

BindingExpression bindingExpression = textBox1.GetBindingExpression(TextBox.TextProperty); BindingExpression bindingExpression = textBox1.GetBindingExpression(TextBox.TextProperty); Binding parentBinding = bindingExpression.ParentBinding; 绑定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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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