IValueConverter计算TextBlock的新大小

时间:2019-01-30 07:36:44

标签: c# wpf xaml resize ivalueconverter

我正在尝试使用IValueConverter来计算TextBlock的新宽度,具体取决于网格上的宽度。但我总是会遇到这种异常:

PresentationFramework.dll中发生了类型为'System.Windows.Markup.XamlParseException'的未处理异常 附加信息:“在'System.Windows.Markup.StaticResourceHolder'上提供值”引发了异常。行号“ 264”和行位置“ 76”。

我将CalMeetingSize缩小为所有内容,但仍然收到错误。所以我认为我在xml中做错了什么?有人可以给我提示吗?

<Grid x:Name="CalBackGround" Margin="163,30,0,0">   

...

<TextBlock Height="18" Text="{Binding subject}" 
   Width="{Binding Path=Width,  
   ElementName=CalBackGround,  
   Converter={StaticResource CalMeetingSizeKey}}"
/>

...

<Window.Resources>
    <local:CalMeetingSize x:Key="CalMeetingSizeKey"/>
</Window.Resources>

...

public class CalMeetingSize : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return 200;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

2 个答案:

答案 0 :(得分:0)

您需要绑定到CalBackGround的ActualWidth属性,而不是Width

答案 1 :(得分:0)

检查是否在XAML中首次使用Window.Resources之前声明了它,以便知道它。 添加资源后,再使用一次即可构建您的应用程序,这有时可以帮助解决构建错误

您也不得绑定到元素的Width,而必须绑定到其ActualWidth。宽度已初始化为NaN,在这里不起作用。