[英]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.