开发者

Usercontrol Basic Property Binding

HI,

I have a Silverlight UserControl where I bind the UserControl.Background property to a border element within it. I found an easy way to bind the background like that :

<UserControl x:Name="root"
    x:Class="TestProject.MyControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="Red"  >

   <Border x:Name="brdMain" Background="{Binding Path=Background, ElementName=root }" >
         etc... .... ...
   </Border>

The problem with that is when I instanciate my UserControl multiple times. I get the following error :

Error: Unhandled Error in Silverlight Application 
Code: 2028    
Category: ParserError       
Message: The name already exists in the tree: root.     
File:      
Line: 0     开发者_Go百科
Position: 0     

So is there any other better way to bind my Usercontrol background property without having to name my UserControl like that : x:Name="root"?

Thanks


Try...

Background="{Binding Background, RelativeSource={RelativeSource AncestorType={x:Type UserControl}, Mode=FindAncestor}}"

EDIT:

Since the above is only valid within WPF (SL only supports TemplatedParent and Self) a varying approach could be taken. You could create a DependencyProperty (propdp is the IntelliSense snippet in Visual Studio) on the UserControl which would set the child Border.Background appropriately.

I'm trying to understand why you want to set the Background on the UserControl though versus simply setting it on the Border and leaving the UserControl empty from a visual stance; allowing it to be the physical container of the child controls which will represent the visuals.


there is ancestor relative binding in Silverlight 5 - http://tonychampion.net/blog/index.php/2011/12/7th-day-of-silverlight-ancestor-relative-source-binding/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜