这是我项目中的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>
答案 0 :(得分:2)
BindingOperations.GetBinding(...)
将为您提供Binding
,ElementName
属于Binding
类的属性。
答案 1 :(得分:1)
BindingExpression bindingExpression = textBox1.GetBindingExpression(TextBox.TextProperty); 绑定parentBinding = bindingExpression.ParentBinding;
答案 2 :(得分: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;
}
答案 3 :(得分: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;