【发布时间】:2023-03-03 23:06:02
【问题描述】:
我想使用 4 个文本框设置用户控件的边框的 BorderThickness,但我无法让它工作。
演示问题的 XAML 代码(仅需要此代码与转换器结合使用):
<Window
x:Class="BorderThicknessBindingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:BorderThicknessBindingTest="clr-namespace:BorderThicknessBindingTest"
Height="300" Width="500">
<Window.Resources>
<BorderThicknessBindingTest:ThicknessConverter x:Key="ThicknessConverter"/>
</Window.Resources>
<Grid Margin="10">
<Border
x:Name="MyBorder"
BorderBrush="Black"
Background="AliceBlue"
BorderThickness="3"/>
<TextBox
HorizontalAlignment="Center" VerticalAlignment="Center"
Text="{Binding Path=BorderThickness.Left, ElementName=MyBorder, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource ThicknessConverter}}"/>
</Grid>
</Window>
需要一个转换器来解析TextBox中输入的字符串:
public class ThicknessConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value; // don't need to do anything here
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
double d;
Double.TryParse((string) value, out d); // Thickness.Left doesn't take a string
return d;
}
}
TextBox 正确显示了厚度的左侧部分,但编辑 TextBox 不会导致边框左侧的呈现方式发生变化。奇怪的是,我在 TextBox 中为 Thickness.Left 设置的值仍然存在,因此该值似乎已设置,但渲染未更新。 在示例代码中,更改 TextBox 中的值,然后调整 Window 的大小,显示左侧边框确实占用了额外的空间,但这个空间是空白的。
有人知道如何解决这个问题吗?
【问题讨论】:
标签: wpf data-binding border margin thickness