日期:2014-05-18  浏览次数:20836 次

wpf 自定义控件的应用
我自定义了一个控件,然后想在Window中应用这个控件(设置属性),程序提示出错,说找不到属性,能帮忙看看什么原因么?
下面是我的自定义控件,包括一个checkbox,一个textblock。我希望在以后应用的时候可以设置textblock的Text属性:
C# code

<UserControl x:Class="Test02.UC"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Test02"
    Height="300" Width="300">
    <StackPanel>
        <CheckBox x:Name="Chb" Content="Chb_Content"/>
        <TextBlock x:Name="Tb" Text="Tb_Content"/>
    </StackPanel>
</UserControl>


以下在Window中应用控件:
<Window x:Class="Test02.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Height="300" Width="300"
  xmlns:local="clr-namespace:Test02">
  <Grid>
  <local:UC Background="LightBlue">
  <local:UC.Tb Text="ABC"/>
  </local:UC>
  </Grid>
</Window>
提示:Error
1 The tag 'UC.Tb' does not exist in XML namespace 'clr-namespace:Test02'. Line 8 Position 14.

请问这是什么原因呢?我在UC这个自定义控件的xaml部分已经定义了Tb啊,我尝试在C#代码部分对Tb进行包装:
C# code
public TextBlock TB
{
    set{this.Tb = value;}
    get{return this.Tb;}
}


C# code
    <Grid>
        <local:UC Background="LightBlue">
            <local:UC.TB Text="ABC"/>
        </local:UC>
    </Grid>

但是提示:Error 1 Cannot set properties on property elements. Line 8 Position 14.

请问如果我需要在使用自定义控件的时候,设置其属性应该怎么做呢?
谢谢。

------解决方案--------------------
<local:UC Background="LightBlue">
<local:UC.Tb Text="ABC"/>
</local:UC>
 
 看了半天,发现Tb是个string.
<local:UC Background="LightBlue" Tb="ABC"/>