我正在创建一个包含InkCanvas
的CustomControl。现在的问题是如何将InkToolbar
(位于CustomControl外部)链接到InkCanvas
(位于CustomControl内部)?
解决方案尝试:
我尝试使用下面的代码在CustomControl之外获取InkCanvas
,但它不起作用。
这是我的代码(使用我尝试过的解决方案不起作用):
//In CustomControl Code Behind
InkCanvas PATH_INK_CANVAS;
protected override void OnApplyTemplate()
{
PATH_INK_CANVAS = GetTemplateChild<InkCanvas>("PATH_INK_CANVAS");
}
T GetTemplateChild<T>(string elementName) where T : DependencyObject
{
var element = GetTemplateChild(elementName) as T;
if (element == null)
throw new NullReferenceException(elementName);
return element;
}
public InkCanvas InkCanvas
{
get { return PATH_INK_CANVAS; }
}
public static readonly DependencyProperty InkCanvasProperty =
DependencyProperty.Register("InkCanvas", typeof(InkCanvas), typeof(RichInkTextBox), new PropertyMetadata(0));
//In CustomControl XAML
<Style>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid Name="MainGrid" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
<InkCanvas Name="PATH_INK_CANVAS" Canvas.ZIndex="-1"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
//In Page
<local:CustomControl x:Name="MyCustomControl"/>
<InkToolbar Grid.Row="0" TargetInkCanvas="{x:Bind MyCustomControl.InkCanvas}"/>
最佳答案
我认为这不是定义只读依赖项属性的正确语法。尝试以下类似的方法-
public InkCanvas InkCanvas
{
get => (InkCanvas)GetValue(InkCanvasProperty);
private set => SetValue(InkCanvasProperty, value);
}
public static readonly DependencyProperty InkCanvasProperty = DependencyProperty.Register(
"InkCanvas", typeof(InkCanvas), typeof(InkCanvasWrapper), new PropertyMetadata(null));
另外,请确保将
Mode
的x:Bind
设置为OneWay
,因为InkCanvas
依赖项属性的默认值是null
(您将默认值设置为0
,这是错误的)。<InkToolbar Grid.Row="0" TargetInkCanvas="{x:Bind MyCustomControl.InkCanvas, Mode=OneWay}" />