簡體   English   中英

通過代碼從XAML獲取綁定的ElementName

[英]Get ElementName of Binding from XAML through code

這是我的項目中的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>

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM