所以我在generic.xaml中的ControlTemplate看起来像
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:NumericStepperControl;assembly=NumericStepperControl"> <Style targettype="local:NumericStepper"> <Setter Property="Template"> <Setter.Value> <ControlTemplate targettype="local:NumericStepper"> <GrID> <GrID.ColumnDeFinitions> <ColumnDeFinition /> <ColumnDeFinition /> </GrID.ColumnDeFinitions> <border GrID.Column="0" borderBrush="Black" borderThickness="2" WIDth="50" Height="30"> <TextBlock WIDth="50" Height="30" Text="{TemplateBinding Value}" /> </border> </GrID> </ControlTemplate> </Setter.Value> </Setter> </Style></ResourceDictionary>
我的控件类看起来像:
namespace NumericStepperControl{ public class NumericStepper : Control { public static Readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value",typeof(int),typeof(NumericStepper),new PropertyMetadata(20)); public NumericStepper() : base() { DefaultStyleKey = typeof( NumericStepper ); } public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty,value); } } }}
我期待这个运行时TextBlock将显示数字20.任何想法为什么这不起作用?
作为一方,我没有一个单独的项目,其中包含对NumericStepperControl程序集的引用,并且当它运行时,控件似乎正确构建.
编辑…经过一些调查,我发现如果我将Value属性的类型更改为一个正常工作的字符串.为什么文本块不仅仅在传入任何内容时调用toString?有没有办法围绕这个,因为我可以看到它发生了很多?
解决方法@H_404_29@ 经过一番挖掘后发现TextBlock实际上并没有在传入的任何内容上调用ToString.要解决这个问题,你必须使用Converter为你调用ToString.尽管如此,TemplateBinding不支持转换器.您必须将TemplateBinding添加到DataContext,然后在Text属性中使用常规Binding以及转换器.
所以TextBlock标记就变成了
<TextBlock WIDth="50" Height="30" DataContext="{TemplateBinding Value}" Text="{Binding Converter={StaticResource NumberTypetoStringConverter}}" />
我的定制转换器:
public class NumberTypetoStringConverter : IValueConverter { public object Convert(object value,Type targettype,object parameter,CultureInfo culture) { if (value == null) { throw new NullReferenceException(); } return value.ToString(); } public object ConvertBack(object value,CultureInfo culture) { MethodInfo methodInfo = targettype.getmethod("Parse"); if (methodInfo == null) { throw new MissingMethodException("The targettype to convert back to a Number must implement a Parse method"); } return methodInfo.Invoke(null,new object[] { value }); } }
这似乎是一种解决方法,我有兴趣听听它是否有任何不利影响.此外,如果有人正在阅读这个,我的转换器有任何问题,请告诉我.
干杯
总结以上是内存溢出为你收集整理的silverlight-2.0 – 自定义控件中的TemplateBindings全部内容,希望文章能够帮你解决silverlight-2.0 – 自定义控件中的TemplateBindings所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)