2012-11-05 101 views
0

我有一个用户控件,看起来像这样的代码:绑定的字符串属性给TextBlock

using System; 
using System.Windows; 
using System.Windows.Controls; 

namespace Client 
{ 
    public partial class Spectrum : UserControl 
    { 
     public string AntennaName { get; set; } 

     public Spectrum() 
     { 
      InitializeComponent(); 
     } 
    } 
} 

和XAML(不是全部,但重要的部分):

<UserControl x:Class="Client.Spectrum" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:Client" 
      mc:Ignorable="d" d:DesignHeight="150" d:DesignWidth="350" 
      Background="#253121" BorderBrush="Black" BorderThickness="1" 
      DataContext="{Binding RelativeSource={RelativeSource Self}}"> 
    <StackPanel 
     <TextBlock Margin="10,3,0,0" Foreground="White" 
        FontWeight="Bold" FontStyle="Italic" TextAlignment="Left" 
        Text="{Binding AntennaName}"/> 
    </StackPanel> 
</UserControl> 

你可以看到即时尝试将AntennaName属性绑定到TextBlock.Text属性,但没有多少运气。 你能告诉我我做错了什么?

+1

您有什么问题? – SLaks

+1

TextBlock.Text不会根据AntennaName更改而更改 –

+0

“Spectrum”类的实例是否设置为View的DataContext? – sll

回答

3

当属性更改时,您没有任何方式通知绑定系统。

您应该创建一个依赖项属性,该属性将自动使用WPF中的现有通知系统。
为此,请输入propdp并按标签激活Visual Studio的内置代码片段。

或者,创建一个单独的ViewModel类并实现INotifyPropertyChanged。

+0

你能告诉我怎么做,而我的用户控件已经继承了“UserControl”类吗? –

+0

一个userControl是一个DependencyObject,所以你可以使用propdp快捷方式 – Sukram

+1

我不知道你可以使用'propdp'自动构建一个'DependencyProperty',谢谢:) – Rachel

0

Exampel:

public partial class MyControl: UserControl 
{ 
    public CoalParameterGrid() 
    { 
    InitializeComponent(); 
    } 

    public static DependencyProperty DarkBackgroundProperty = DependencyProperty.Register("DarkBackground", typeof(Brush), typeof(MyControl)); 

    public Brush DarkBackground 
    { 
    get 
    { 
     return (Brush)GetValue(DarkBackgroundProperty); 
    } 
    set 
    { 
     SetValue(DarkBackgroundProperty, value); 
    } 
    } 
} 
相关问题