2012-11-05 100 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); 
    } 
    } 
} 
相關問題