我做了下面的问题,这个问题已经有答案了,
WPF:尝试添加一个类到窗口。资源再次
但是还有另一个问题:当我试图通过样式资源访问"CenterToolTipConverter"方法时,消息出现:"资源无法解析"
CenterToolTipConverter.cs
namespace WpfApplication1
{
public class CenterToolTipConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.FirstOrDefault(v => v == DependencyProperty.UnsetValue) != null)
{
return double.NaN;
}
double placementTargetWidth = (double)values[0];
double toolTipWidth = (double)values[1];
return (placementTargetWidth / 2.0) - (toolTipWidth / 2.0);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1;assembly=WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:CenterToolTipConverter x:Key="myCenterToolTipConverter"/>
</Window.Resources>
</Window>
直到这里,没有问题。然而,当我尝试访问"CenterToolTipConverter"方法时,在:
Styles.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Style TargetType="{x:Type ToolTip}">
<Setter Property="HorizontalOffset">
<Setter.Value>
<MultiBinding Converter="{StaticResource myCenterToolTipConverter}">
<Binding RelativeSource="{RelativeSource Self}" Path="PlacementTarget.ActualWidth"/>
<Binding RelativeSource="{RelativeSource Self}" Path="ActualWidth"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
消息错误发生("资源无法解析")。这里出了什么问题?提前感谢!!
您在Window
中添加转换器作为资源,但ResourceDictionary
不知道Window
中定义的资源。
在ResourceDictionary
中定义转换器,或者在应用程序级别将这两个资源添加到App.xaml.