2016-08-01 26 views
0

这是我的项目的XAML片段:
获得通过代码从XAML绑定的ElementName

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

回答

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

BindingOperations.GetBinding(...)会给你Binding,并ElementNameBinding类的属性。

1

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

+0

任何想法,这可怎么在MultiBinding方案中完成? –

+0

对于多重绑定,您可以使用以下代码: 'MultiBinding bindingExpression = BindingOperations.GetMultiBinding(txtSample,TextBox.TextProperty); 收藏 parentBinding = bindingExpression.Bindings;' –

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