Wpf 绑定同级控件并在转换器中使用
假设我有工作代码Wpf 绑定同级控件并在转换器中使用,wpf,xaml,telerik,Wpf,Xaml,Telerik,假设我有工作代码 <StackPanel> <TextBox x:Name="txt" Text="{Binding MyText}"/> <TextBlock Text="Some text" Visibility="{Binding Text, ElementName=txt, Converter={StaticResource BooleanToVisibilityConverter}}"/> </StackPanel>
<StackPanel>
<TextBox x:Name="txt" Text="{Binding MyText}"/>
<TextBlock Text="Some text" Visibility="{Binding Text, ElementName=txt, Converter={StaticResource BooleanToVisibilityConverter}}"/>
</StackPanel>
它绑定文本框的属性。但是现在我想绑定TextBox控件本身,而不是属性本身,然后在转换器中使用它。原因是我想在转换器中获取文本框的LineCount属性
我们可以吗
更新
实际上,文本框位于GridViewColumn中
<telerik:GridViewColumn>
<telerik.GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox....
LineCount
属性不仅在您更改TextBox
的文本时,而且在TextBox
的布局更改(例如尺寸)时更改其值。这取决于TextBox
的TextWrapping
属性
如果您想要一个可重用且完整的解决方案,我建议您为文本框
创建一个行为
,它公开了一个可以绑定的可观察的依赖属性
以下是此类行为的一个示例:
class LineCountBehavior : Behavior<TextBox>
{
public static readonly DependencyProperty LineCountProperty =
DependencyProperty.Register(
"LineCount",
typeof(int),
typeof(LineCountBehavior),
new PropertyMetadata(0));
public int LineCount
{
get { return (int)GetValue(LineCountProperty); }
set { SetValue(LineCountProperty, value); }
}
protected override void OnAttached()
{
AssociatedObject.LayoutUpdated += LineCountChanged;
AssociatedObject.TextChanged += LineCountChanged;
}
protected override void OnDetaching()
{
AssociatedObject.LayoutUpdated -= LineCountChanged;
AssociatedObject.TextChanged -= LineCountChanged;
}
private void LineCountChanged(object sender, EventArgs e)
{
LineCount = AssociatedObject.LineCount;
}
}
类LineCountBehavior:行为
{
公共静态只读DependencyProperty LineCountProperty=
从属属性。寄存器(
“行数”,
类型(int),
类型(LineCountBehavior),
新属性元数据(0);
公共整数行数
{
获取{return(int)GetValue(LineCountProperty);}
set{SetValue(LineCountProperty,value);}
}
受保护的覆盖无效附加()
{
AssociatedObject.LayoutUpdated+=LineCountChanged;
AssociatedObject.TextChanged+=LineCountChanged;
}
附加时受保护的覆盖无效()
{
AssociatedObject.LayoutUpdated-=LineCountChanged;
AssociatedObject.TextChanged-=LineCountChanged;
}
私有void LineCountChanged(对象发送方,事件参数e)
{
LineCount=AssociatedObject.LineCount;
}
}
用法示例:
<TextBox x:Name="TextBox" AcceptsReturn="True" TextWrapping="Wrap">
<i:Interaction.Behaviors>
<l:LineCountBehavior x:Name="LineCountBehavior"/>
</i:Interaction.Behaviors>
</TextBox>
<TextBlock Visibility="{Binding LineCount, ElementName=LineCountBehavior, Converter={StaticResource IntToVisibilityConverter}}"/>
是。只需删除文本,
。使用{Binding ElementName=txt,Converter…}
只需从绑定中删除属性路径。但是,您将不会收到任何更改通知。也许最好对文本和行数使用多重绑定。前者用于更改通知,后者用于行计数。如果您想重用这些东西(例如,您有许多文本框
需要以这种方式观察),最好创建一个行为
或一个附加属性。请查看更新的内容…感谢您的回复。实际上,文本框位于RadGridView列中。我不确定它是否有效?