WPF - 将转换器应用于所有文本框
使用 WPF,我想在所有 TextBox 内的 Text 属性的绑定中应用转换器。
以下内容适用于单个文本框:
<TextBox Style="{StaticResource TextBoxStyleBase2}"
Text="{Binding Text, Converter={StaticResource MyConverter}}">
</TextBox>
但是,我们的文本框使用带有控件模板的样式,如下所示:
<Grid>
<Border x:Name="Border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{StaticResource DefaultCornerRadius}">
<Grid>
<Border BorderThickness="1">
<ScrollViewer x:Name="PART_ContentHost" Margin="0"/>
</Border>
</Grid>
</Border>
</Grid>
如何使用此模板应用我的转换器? 谢谢!
Using WPF, I want to apply a converter within the binding of the Text property within all my TextBoxes.
The following works for a single TextBox:
<TextBox Style="{StaticResource TextBoxStyleBase2}"
Text="{Binding Text, Converter={StaticResource MyConverter}}">
</TextBox>
However, our TextBoxes uses a style with a Control Template that looks like this:
<Grid>
<Border x:Name="Border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{StaticResource DefaultCornerRadius}">
<Grid>
<Border BorderThickness="1">
<ScrollViewer x:Name="PART_ContentHost" Margin="0"/>
</Border>
</Grid>
</Border>
</Grid>
How can I apply my converter using this Template?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
任何从
ControlTemplate
内部修改TextBox
属性的尝试都会很混乱,因此我建议您在Style
而不是中进行操作。 ControlTemplate
如果可能的话。我将首先解释如何使用Style
执行此操作,然后解释如何在必要时调整该技术以在ControlTemplate
中使用。您需要做的是创建一个可以像这样使用的附加属性:
ConverterInstaller 类有一个简单的附加属性,它将转换器安装到最初在
TextBox
:这里唯一的复杂性是:
要将此属性附加到 ControlTemplate 内的元素而不是在样式中执行此操作,请使用相同的代码,除了传递到 PropertyChangedCallback 的原始对象被强制转换
var element = ( FrameworkElement)obj;
并在 Dispatcher.BeginInvoke 操作中使用var box = (TextBox)element.TemplatedParent;
找到实际的 TextBoxAny attempt to modify
TextBox
properties from inside theControlTemplate
will be messy, so I recommend you do it in theStyle
instead of theControlTemplate
if at all possible. I'll start by explaining how to do it with aStyle
then explain how to adapt the technique for use in aControlTemplate
if necessary.What you need to do is create an attached property that can be used like this:
The
ConverterInstaller
class has a simple attached property that installs the converter into anyBinding
initially set on theTextBox
:The only complexity here is:
To attach this property to an element inside the ControlTemplate instead of doing it in the style, the same code is used except the original object passed into the PropertyChangedCallback is cast
var element = (FrameworkElement)obj;
and inside the Dispatcher.BeginInvoke action the actual TextBox is found withvar box = (TextBox)element.TemplatedParent;