我们的项目需要我们绑定控件的许多属性,例如Height
, Width
, MinHeight
, Row
, Column
, rowspan
... 等。这样做时,我们观察到绑定错误,这些值是null
我们将从 DB 获取的值。
为了说明,我的MainWindow.xaml.cs看起来像这样。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//TextWidth id null
TextBlockSize1 = new ItemSize() { TextHeight=20 };
//TextWidth is null
TextBlockSize2 = new ItemSize() { TextWidth = 40 };
//TextHeight is null and TextWidth is null
TextBlockSize3 = new ItemSize() { TextWidth = 40 };
textblock1.DataContext = TextBlockSize1;
textblock2.DataContext = TextBlockSize2;
textblock3.DataContext = TextBlockSize3;
}
public ItemSize TextBlockSize1 { get; set; }
public ItemSize TextBlockSize2 { get; set; }
public ItemSize TextBlockSize3 { get; set; }
}
public class ItemSize
{
public double? TextHeight { get; set; }
public double? TextWidth { get; set; }
}
MainWindow.xaml看起来像这样。
<Window x:Class="WPfAppln1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctrl="clr-namespace:WPfAppln1.Controls"
Title="MainWindow" Height="350" Width="525">
<StackPanel >
<TextBlock Name="textblock1" Text=" TextBlock 1" Width="{Binding TextWidth}" Height="{Binding TextHeight}"></TextBlock>
<TextBlock Name="textblock2" Text=" TextBlock 2" Width="{Binding TextWidth}" Height="{Binding TextHeight}"></TextBlock>
<TextBlock Name="textblock3" Text=" TextBlock 3" Width="{Binding TextWidth, TargetNullValue=Auto}" Height="{Binding TextHeight, TargetNullValue=Auto}"></TextBlock>
</StackPanel>
</Window>
在输出窗口中显示了以下绑定错误:
System.Windows.Data Error: 5 : 'WPfAppln1.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Numerics\v4.0_4.0.0.0__b77a5c561934e089\System.Numerics.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Value produced by BindingExpression is not valid for target property.; Value='<null>' BindingExpression:Path=TextWidth; DataItem='ItemSize' (HashCode=43929715); target element is 'TextBlock' (Name='textblock1'); target property is 'Width' (type 'Double')
System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='<null>' BindingExpression:Path=TextHeight; DataItem='ItemSize' (HashCode=57104612); target element is 'TextBlock' (Name='textblock2'); target property is 'Height' (type 'Double')
System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='<null>' BindingExpression:Path=TextHeight; DataItem='ItemSize' (HashCode=59587750); target element is 'TextBlock' (Name='textblock3'); target property is 'Height' (type 'Double')
The thread '<No Name>' (0x2c60) has exited with code 0 (0x0).
由于这些错误,应用程序需要很长时间才能加载屏幕。
所以问题是如何在绑定到 wpf 控件时容纳可为空的值,以及如何在绑定值为空时为控件的宽度属性提供默认值,例如“自动”。