WPF中应用ResourceDictionary样式的TextBox绑定失效如何解决
WPF自定义TextBox样式后数据绑定失效问题
前置代码
我使用ResourceDictionary为TextBox自定义样式,并已在App.xaml中完成注册:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style TargetType="{x:Type TextBox}" x:Key="TextBoxTheme"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TextBox}"> <Border CornerRadius="12" Background="#2E3135" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"> <Grid> <TextBox BorderThickness="0" Background="Transparent" VerticalContentAlignment="Center" Padding="20,0,20,0" Foreground="#B8BDC1" /> </Grid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary>
App.xaml注册代码:
<Application x:Class="Paraject.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Paraject" StartupUri="/MVVM/Views/Windows/LoginWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/UiDesign/Theme/TextBoxTheme.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
页面中使用样式的TextBox代码:
<TextBox x:Name="UsernameTextbox" Grid.Row="2" Width="303" Height="38" Margin="0,0,0,30" FontSize="15" Text="{Binding Path=CurrentUserAccount.Username}" Style="{StaticResource TextBoxTheme}" />
问题现象
应用自定义样式后,TextBox的Text属性数据绑定失效,输入内容无法同步到绑定源(下方截图中MessageBox为点击按钮后弹出的验证结果):
- 应用样式运行结果:输入内容后绑定的属性值为空

- 移除样式运行结果:输入内容可正常同步到绑定属性

尝试直接给样式内层的TextBox添加Text="{TemplateBinding Text}",绑定依旧无法生效。
解决方案
将样式内层TextBox的Text属性改用以下绑定方式即可修复:
<TextBox Text="{Binding Path=Text, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" BorderThickness="0" Background="Transparent" VerticalContentAlignment="Center" Padding="20,0,20,0" Foreground="#B8BDC1" CaretBrush="#B8BDC1" />
原因说明
TemplateBinding是WPF中用于控件模板的轻量绑定,默认仅支持单向值同步,无法将内层TextBox的输入内容回传到外层应用样式的TextBox实例上,因此外层的数据源绑定无法拿到最新值。改用显式指向模板父级的绑定,并手动指定双向同步模式、属性变更时立即触发源更新,就可以实现值的双向传递,解决绑定失效问题。
内容的提问来源于stack exchange,提问作者jd0x0021
相关产品推荐
相关产品推荐

