2011-07-22 62 views
1

我在我的App.xaml文件中定義了以下自定義按鈕。WPF將從ControlTemplate綁定到代碼後面的代碼

<Style x:Key="DispatchListCallButton" TargetType="Button"> 
     <Setter Property="OverridesDefaultStyle" Value="True"/> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="Button"> 
        <Border Name="outerBorder" BorderThickness="1" BorderBrush="DimGray" CornerRadius="1" Background="{TemplateBinding Background}"> 
         <Border Name="innerBorder" BorderThickness="1" BorderBrush="WhiteSmoke" CornerRadius="1" Background="{TemplateBinding Background}"> 
          <Grid Margin="2"> 
           <Grid.RowDefinitions> 
            <RowDefinition Height="1*"></RowDefinition> 
            <RowDefinition Height="2*"></RowDefinition> 
            <RowDefinition Height="Auto"></RowDefinition> 
            <RowDefinition Height="1*"></RowDefinition> 
           </Grid.RowDefinitions> 
           <StackPanel Orientation="Horizontal"> 
            <TextBlock>2600</TextBlock> 
            <TextBlock Margin="4,0,0,0">IPRJ</TextBlock> 
           </StackPanel> 
           <TextBlock Grid.Row="1" TextWrapping="Wrap">1234 Main St West Avenue</TextBlock> 
           <Rectangle Grid.Row="2" Height="1" Margin="2,0,2,0" Stroke="DarkGray" /> 
           <StackPanel Grid.Row="3" Orientation="Horizontal" HorizontalAlignment="Right"> 
            <TextBlock>1</TextBlock> 
            <TextBlock Margin="4,0,0,0">*</TextBlock> 
           </StackPanel> 
           <ContentPresenter HorizontalAlignment="Stretch" VerticalAlignment="Center" Name="content"/> 
          </Grid> 
         </Border> 
        </Border> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

因爲我沒有問題,所以我沒有觸發觸發器。

這顯示了我想要的東西,接受所有的值都是硬編碼的。總共有5個TextBlock作爲這個Button的一部分。我希望能夠爲這5個文本塊中的每一個設置綁定,以便我可以在後面的代碼中動態設置它們。理想情況下,這是我希望我的代碼看起來像。

 DispatchListCallButton newButton = new DispatchListCallButton(); 

     // Set the 5 TextBlock values 
     newButton.Id = "4444"; 
     newButton.Code = "ABCD"; 
     newButton.Address = "2000 Main"; 
     newButton.Priority = 5; 
     newButton.Symbol = "*"; 

我該怎麼做,以及ControlTemplate中的綁定表達式看起來像什麼?

回答

0

您可以通過以下兩種方法之一來完成此操作。

第一種方法: 首先,您需要創建從Button繼承的控件類型,因爲您無法按照您現在嘗試的樣式修改按鈕(或實例化)。 然後你會定義ID,代碼等。作爲控件的DependencyProperties。如果它們是DependencyProperties,那麼代碼將自動註冊以偵聽更改。

文章: http://msdn.microsoft.com/en-us/library/ms753358.aspx

第二種方法: 你會定義一個公開這些屬性,並實現INotifyPropertyChange按鈕一個視圖模型。每次設置屬性時,發起事件。然後,您將newButton.DataContext設置爲ViewModel的一個實例並修改視圖模型。綁定會像文本= {綁定地址}

文章: http://msdn.microsoft.com/en-us/library/ms229614.aspx

+0

謝謝。什麼方法是「首選」,更容易處理。我在其他地方使用了第一種方法,但不希望爲此需要複雜化。 – WPFNewbie

+0

我會推薦第二種方法。它更接近WPF的Model-View-ViewModel設計模式,如果您稍後決定更改顯示類型,它將更加靈活。 – JMcCarty

+0

我看到很多有關MVVM的描述,但是我找不到一個很好的簡單實例源代碼。你有什麼例子嗎? – WPFNewbie

相關問題