Reputation: 1059
For example I have a UserControl
like this:
<UserControl x:Class="SMPlayer.ScrollingTextBlock">
<ScrollViewer
x:Name="TextScrollViewer"
HorizontalScrollBarVisibility="Hidden"
PointerEntered="TextScrollViewer_PointerEntered"
VerticalScrollBarVisibility="Disabled">
<StackPanel>
<TextBlock x:Name="NormalTextBlock" />
<TextBlock x:Name="PointerOverTextBlock" Visibility="Collapsed" />
</StackPanel>
</ScrollViewer>
</UserControl>
I want this UserControl
still to be treated as a normal TextBlock
. For example <ScrollingTextBlock Text="Something"/>
. It is just a TextBlock
with more functionalities, or in other words, another control that inherits from TextBlock
. Because there are a lot of properties, I don't want to do this manually by adding DependencyProperty
and do things like public string Text { get; set; }
. It is just too much work.
How can I achieve that? I think this question might have been asked but I am not sure how to properly paraphrase it.
Upvotes: 1
Views: 387
Reputation: 4943
If you want your control to "be treated as a normal TextBlock
", then you don't have any other choice than inheriting from TextBlock
. This is what inheritance is for.
Otherwise you indeed have to add properties to your UserControl
and bind them by yourself, even though this is a lot of work this is due to the poor flexibility of the UserControl
. You cannot have a Text
property on an object unless it inherits from a TextBlock
or you add it yourself.
Alternatively you can use templating to re-template a ContentControl
like this:
public class ScrollingContent : ContentControl { }
<Window.Resources>
<Style TargetType="local:ScrollingContent">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:ScrollingContent">
<ScrollViewer
x:Name="TextScrollViewer"
HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Disabled">
<StackPanel>
<TextBlock x:Name="NormalTextBlock" />
<ContentPresenter></ContentPresenter>
</StackPanel>
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<local:ScrollingContent>
<TextBlock Text="Whatever control I want" Foreground="Red"></TextBlock>
</local:ScrollingContent>
</Grid>
But then again, your control is not really a TextBlock
.
Upvotes: 1
Reputation: 5868
If you want to implement <ScrollingTextBlock Text="Something"/>
in UserControl, you still need to add DependencyProperty to achieve it.
Upvotes: 1