C# XAML转换器没有';行不通
我有一个C# XAML转换器没有';行不通,c#,xaml,windows-8,ivalueconverter,C#,Xaml,Windows 8,Ivalueconverter,我有一个ScreenHeightConverter,想在GridView的ItemHeight上使用它 但我不知道我是否正确使用它,因为如果我调试它,它甚至不会跳转到转换器 我的代码: public class ScreenHeightConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) {
ScreenHeightConverter
,想在GridView的ItemHeight
上使用它
但我不知道我是否正确使用它,因为如果我调试它,它甚至不会跳转到转换器
我的代码:
public class ScreenHeightConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
double ScreenHeight = (int)Window.Current.Bounds.Height;
double factor = 1050/(double)value;
return (int)(ScreenHeight/factor);
}
}
<VariableSizedWrapGrid Margin="3" ItemHeight="{Binding '80',Converter={StaticResource ScreenHeightConverter}}" ItemWidth="255"/>
公共类屏幕高度转换器:IValueConverter
{
公共对象转换(对象值、类型targetType、对象参数、字符串语言)
{
双屏幕高度=(int)Window.Current.Bounds.Height;
双因子=1050/(双)值;
返回值(整数)(屏幕高度/系数);
}
}
您需要为转换器创建一个资源
首先,您需要添加。范例
接下来,您需要将资源添加到适当的位置(UserControl
、Window
、App
或其他对象)
未以正确的方式指定您的绑定
您当前指定绑定的方式是,在当前通过DataContext
属性设置/继承的对象上查找一个名为80的属性(即Path
),并使用其值
(属性名不能以数字开头,我认为引用的语法表示路径
可能无论如何都是错误的…因此绑定
是错误的…并且您的转换器不会被调用)
要确认这一点,您可以在调试应用程序时查看Visual Studio中的“输出”窗口……它应该会通知您有错误的绑定……有关详细信息,请参阅以下链接:
我相信你的目的是要有一个文字常量值,它被传递给你的转换器,以便计算出一个合适的值
与其使用转换器
,不如考虑使用标记扩展
…是的,您可以通过绑定到任意对象并将80值作为转换器参数
传递给转换器来“捏造”…但这不是最好的方法,也是一个大难题
以下是有关编写MarkupExtension的一些链接:
…因此创建一个MarkupExtension
派生类,例如HeightAdjustedExtension:MarkupExtension。。。。在扩展上执行ProvideValue
方法和“属性”,以收集传入数据
…然后你可以这样使用它
ItemHeight="{myns:HeightAdjusted 80}"
这不是经过测试的,但类似这样的东西(给你一些可以玩的东西):
对不起,我忘了提到,应用程序资源中的转换器已准备就绪。谢谢,你说得对。如果我用ConverterParameter来做,这确实不是最好的方法,但我不知道MarkupExtension是否是一种替代方法。我想在很多地方使用这个ConverterParameter,来确定平板电脑和其他结果的高度和宽度。
<UserControl.Resources>
<converter:ScreenHeightConverter x:key="screenHeightConverter"/>
</UserControl.Resources>
<VariableSizedWrapGrid Margin="3" ItemHeight="{Binding '80',Converter={StaticResource screenHeightConverter}}" ItemWidth="255"/>
ItemHeight="{myns:HeightAdjusted 80}"
public class HeightAdjustedExtension : MarkupExtension
{
[ConstructorArgument("height")]
public string Height { get; set; }
public HeightAdjustedExtension () { }
public HeightAdjustedExtension (string height)
{
Height = height;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
int theheight;
int.TryParse( Height, out theheight );
double ScreenHeight = (int)Window.Current.Bounds.Height;
double factor = 1050/(double)theheight ;
return (int)(ScreenHeight/factor);
}
}