[英]How to pass values from a usercontrol to a customcontrol using style in Generic.xaml?
在尝试创建一个接受字符串(文本)的简单customcontrol时,我很难通过Generic.xaml中的样式将值从XAML传递到customcontrol。
调用XAML可以:
<wc:ccTestFigure Text="{Binding Text, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
ccTestFigure定义为:
public class ccTestFigure : FrameworkElement
{
public static readonly DependencyProperty TextProperty =
TextBlock.TextProperty.AddOwner(typeof(ccTestFigure));
public String Text
{
get { return (String)this.GetValue(TextProperty); }
set { this.SetValue(TextProperty, value); }
}
static ccTestFigure()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ccTestFigure), new FrameworkPropertyMetadata(typeof(ccTestFigure)));
}
public ccTestFigure()
{
var typeface = new Typeface(
FontFamily,
FontStyle,
FontWeights.Normal,
FontStretches.Normal);
ft = new FormattedText(
Text,
System.Threading.Thread.CurrentThread.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
FontSize,
Foreground);
}
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
drawingContext.DrawText(ft, new Point());
}
Generic.xaml中的Style不喜欢TemplateBinding,所以我无所适从如何将Text从usercontrol传递到customControl ccTestFigure。
到目前为止,我拥有的样式(不起作用)是:
<Style TargetType="{x:Type local:ccTestFigure}">
<Setter Property="Text" Value="{Binding Text, RelativeSource={RelativeSource Self}}"/>
</Style>
其中文本是一个简单的字符串。
感谢您的帮助。 提前致谢。
看起来您正在尝试做一些完全多余的事情,将“ Text”的值设置为其自身。
问题是,当“文本”更改时,您没有更新“ ft”。 添加一个属性更改处理程序,然后将带格式文本的内容而不是构造函数放在其中:
public static readonly DependencyProperty TextProperty =
TextBlock.TextProperty.AddOwner(typeof(ccTestFigure), new FrameworkPropertyMetadata(propertyChangedCallback: OnTextChanged));
private static void OnTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
((ccTestFigure)sender).UpdateText();
}
private void UpdateText()
{
var typeface = new Typeface(
FontFamily,
FontStyle,
FontWeights.Normal,
FontStretches.Normal);
ft = new FormattedText(
Text,
System.Threading.Thread.CurrentThread.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
FontSize,
Foreground);
}
public ccTestFigure()
{
}
我发布此代码,因为我没有其他显示代码的方法。 McGamagle是正确的-只需进行以下一些更改即可。 需要添加“ AffectsRender”以显示文本。
public static readonly DependencyProperty TextProperty =
TextBlock.TextProperty.AddOwner(typeof(ccTextFigure),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure,
propertyChangedCallback: OnTextChanged
));
就我而言,我还需要AffectsMeasure来强制对父滚动查看器进行重新测量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.