2012-04-04 2 views
1

Я пытался связать StringFormat из текста свойства TextBlock для шаблонного родителя.WPF TextBlock StringFormat Связывание Для Родитель

Вот где я пытаюсь установить StringFormat:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:local="clr-namespace:DataFlowControls"> 

    <Style TargetType="{x:Type local:DfcEditTextBox}"> 
     <Setter Property="Margin" Value="-6, 0, -6, 0" /> 
     <Setter Property="FocusVisualStyle" Value="{x:Null}"/> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="{x:Type local:DfcEditTextBox}"> 
        <TextBlock x:Name="PART_TextBlock" 
           Padding="2, 0, 0, 0" 
           Text="{Binding Path=Value, StringFormat=ThisStringFormat, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"> 
        </TextBlock> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

</ResourceDictionary> 

Вот родитель:

<Window x:Class="DataFlowControls.Show.DfcListView" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:dfc="clr-namespace:DataFlowControls;assembly=DataFlowControls" 
     xmlns:local="clr-namespace:DataFlowControls.Show" 
     Title="DfcListView" Height="400" Width="500"> 
    <Grid> 
     <StackPanel> 
      <dfc:DfcListView Name="lvTradesCollection" ItemsSource="{Binding Path=TradesCollection}" KeyboardNavigation.DirectionalNavigation="Continue" > 
       <ListView.ItemContainerStyle> 
        <Style TargetType="ListViewItem"> 
         <Setter Property="HorizontalContentAlignment" Value="Stretch" /> 
        </Style> 
       </ListView.ItemContainerStyle> 
       <ListView.Resources> 
        <DataTemplate x:Key="Date_DataTemplate"> 
         <dfc:DfcEditTextBox Value="{Binding Path=Date, Mode=Twoway, UpdateSourceTrigger=PropertyChanged}" ThisStringFormat='{}{0:dd/MM/yyyy}' HorizontalContentAlignment="Left" IsEditable="true" /> 
        </DataTemplate> 
        <DataTemplate x:Key="Asset_DataTemplate"> 
         <dfc:DfcEditTextBox Value="{Binding Path=Asset, Mode=Twoway, UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Left" IsEditable="true" /> 
        </DataTemplate> 
        <DataTemplate x:Key="Lots_DataTemplate"> 
         <dfc:DfcEditTextBox Value="{Binding Path=Lots, Mode=Twoway, UpdateSourceTrigger=PropertyChanged}" ThisStringFormat='N2' HorizontalContentAlignment="Center" IsEditable="true" /> 
        </DataTemplate> 
        <DataTemplate x:Key="Price_DataTemplate"> 
         <dfc:DfcEditTextBox Value="{Binding Path=Price, Mode=Twoway, UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Center" IsEditable="true" /> 
        </DataTemplate> 
        <DataTemplate x:Key="IsCheap_DataTemplate"> 
         <dfc:DfcEditCheckBox Value="{Binding Path=IsCheap, Mode=Twoway, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" IsEditable="true" /> 
        </DataTemplate> 
        <DataTemplate x:Key="NextTrade_DataTemplate"> 
         <dfc:DfcEditComboBox Value="{Binding Path=NextTrade, Mode=Twoway, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{x:Static local:DfcListView.NextTradeTypes}" IsEditable="true" /> 
        </DataTemplate> 
       </ListView.Resources> 
       <ListView.View> 
        <dfc:DfcGridView> 
         <dfc:DfcGridViewColumn Header="Date" Width="140" CellTemplate="{StaticResource Date_DataTemplate}" /> 
         <dfc:DfcGridViewColumn Header="Asset" Width="40" CellTemplate="{StaticResource Asset_DataTemplate}" /> 
         <dfc:DfcGridViewColumn Header="Lots" Width="40" CellTemplate="{StaticResource Lots_DataTemplate}" /> 
         <dfc:DfcGridViewColumn Header="Price" Width="50" CellTemplate="{StaticResource Price_DataTemplate}" /> 
         <dfc:DfcGridViewColumn Header="IsCheap" Width="60" CellTemplate="{StaticResource IsCheap_DataTemplate}" /> 
         <dfc:DfcGridViewColumn Header="NextTrade" Width="80" CellTemplate="{StaticResource NextTrade_DataTemplate}" />                   
        </dfc:DfcGridView> 
       </ListView.View> 
      </dfc:DfcListView> 
      <Button Content="Add Row" HorizontalAlignment="Left" Margin="5,5,5,5" Click="AddRow_Click"/> 
      <Button Content="Update Row" HorizontalAlignment="Left" Margin="5,5,5,5" Click="UpdateRow_Click"/> 
     </StackPanel> 
    </Grid> 
</Window> 

Все работает отлично, пока я не включать StringFormat = ThisStringFormat, что гадости его , Но мне почему-то нужно связать StringFormat с свойством ThisStringFormat, выраженным в родительском. Я экспериментировал с изменением StringFormat = ThisStringFormat, чтобы попытаться добраться до шаблона родителя, но безрезультатно.

Любые идеи о том, как решить это?

ответ

1

Недвижимость StringFormat является обычным делом на BindingBase, и регулярные свойства не могут быть целями связывания, только свойства зависимостей могут. Поэтому ответ: вы не можете этого сделать.

Некоторые возможные подходы:

  1. Подкласс TextBox и добавить свойство в формат строки зависимостей, к которому вы можете связать предоставление требуемой функциональности
  2. Раздвиньте модель представления (если есть) с FormattedValue собственности (вероятно, немного некрасиво)
  3. Используйте MultiBinding для Text собственности. Одно связывание имеет значение Value, а одно - ThisStringFormat шаблона родителя. Затем напишите конвертор, реализующий IMultiValueConverter, чтобы вернуть форматированное значение.
+1

Третий использовать MultiBinding с IValueConverter. –

+0

Спасибо ... так просто, но так правильно. Я должен был подумать об этом несколько часов назад! – Damian

+0

Это еще не работает ... – Damian