2016-07-01 48 views
2

我是WPF的初學者,我嘗試用DataTrigger編寫WPF部分。Setter Target Name not recognized

這裏所需要的邏輯:

 
If the variable "iBottleCount" >= 10 then make the background of a label green. 
If the variable "iBottleCount" < 10 then make the background of a label yellow. 
If the variable "iBottleCount" = 0 then make the background of a label red. 

但他can'f發現我與targed名 「StatusColor」 的標籤。

找到下面的代碼:

<DataGridTemplateColumn Header="Status" Width="80" > 

<DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
     <Grid> 

      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="20" /> 
       <ColumnDefinition Width="1*" /> 
      </Grid.ColumnDefinitions> 

      <TextBlock x:Name="StatusText" Height="15" HorizontalAlignment="Left" Margin="2,2,2,2" Text="" VerticalAlignment="Top" Grid.Row="0" Grid.Column="1"/> 
      <Label x:Name="StatusColor" Content="" Background="green" HorizontalAlignment="Center" Margin="5,5,5,5" VerticalAlignment="Top" Height="10" Width="20" Grid.Row="0" Grid.Column="0"/> 
     </Grid> 
    </DataTemplate> 
</DataGridTemplateColumn.CellTemplate> 

<DataGridTemplateColumn.CellStyle> 
    <Style TargetType="{x:Type DataGridCell}"> 
     <Style.Triggers> 
      <DataTrigger Binding="{Binding iBottleCount}" Value="=>10"> 

       <!-- PROBLEM IS IN THIS LINE --> 
       <Setter TargetName="StatusColor" Property="Background" Value="Green" /> 
      </DataTrigger> 
     </Style.Triggers> 
    </Style> 
</DataGridTemplateColumn.CellStyle> 

</DataGridTemplateColumn> 

那麼,有什麼問題呢?標籤被定義爲更高的一些行。

+0

我認爲你的錯誤可能在這裏: 10」> 嘗試輸入:Value> =「10」 –

回答

1

模板有自己的範圍,無法從外部訪問。無論如何,您無法在Style觸發器中使用TargetName,如果您需要更改標籤,請在其Style中添加觸發器。

1

沒有一個很好的Minimal, Complete, and Verifiable code example明確顯示你想要做什麼,不可能知道最好的解決方案是什麼。這說&hellip;

首先,在H.B.'s answer的評論是正確的:你要訪問一個名爲元素如該名不在範圍內的地步,你是在試圖訪問它,即使你能中, Style觸發器不能使用TargetName屬性。

當然,一種選擇是將觸發器移動到模板。但是,這需要將模板綁定到您正在使用的視圖模型上。你的情況可能確實如此。這個問題沒有足夠的背景知道。

如果您希望更接近您現在的設計,觸發器的位置爲DataGridCell樣式,則可以使用TemplateBinding完成您想要的操作。例如&hellip;

在模板:

<Label Content="" Background="{TemplateBinding Background}" HorizontalAlignment="Center" 
     Margin="5,5,5,5" VerticalAlignment="Top" Height="10" Width="20" 
     Grid.Row="0" Grid.Column="0"/> 

,然後設置DataGridCellBackground屬性將下降到模板傳播。即在你的風格的觸發器中:

<Setter Property="Background" Value="Green"/> 

I.e.只需從您現有的代碼中刪除TargetName屬性即可。

顯然,這隻有在您想要在模板中設置一個Background值時纔有效。如果您有更復雜的場景,您需要更詳細的內容。另外,當然不要忘記,如果您想爲Background屬性提供默認值,則需要在樣式中包含非觸發<Setter .../>元素以設置該默認值。