2011-07-22 59 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

相关问题