2010-08-08 122 views
0

有沒有辦法在樣式中模板Binding.Converter和Binding.ValidationRules?在模板中設置綁定屬性

例如:我有以下文本框:

  <TextBox x:Name="DepartTime" Height="23" HorizontalContentAlignment="Left" HorizontalAlignment="Left" 
       Margin="3" Width="140" 
       Style="{DynamicResource TimeOfDayTextBox}"> 
       <TextBox.Text> 
        <!-- Textbox notifies changes when Text is changed, and not focus. --> 
        <Binding Path="FlightDepartTime" StringFormat="{}{0:hh:mm tt}" > 
         <Binding.Converter> 
          <convert:TimeOfDayConverter /> 
         </Binding.Converter> 
         <Binding.ValidationRules> 
          <!-- Validation rule set to run when binding target is updated. --> 
          <validate:ValidateTimeOfDay ValidatesOnTargetUpdated="True" /> 
         </Binding.ValidationRules> 
        </Binding> 
       </TextBox.Text> 
      </TextBox> 

。我無法弄清楚如何把轉換器和驗證規則到我TimeOfDayTextBox風格。

很多謝謝。

回答

1

不幸的是,沒有。樣式只能將Text屬性設置爲Binding。它不能設置綁定的屬性。另外,由於綁定不是一個DependencyObject,因此無法設置綁定的樣式。你必須使你的代碼更簡潔

一種選擇是使用用於創建自定義的MarkupExtension綁定你想:

public class TimeOfDayBinding 
    : MarkupExtension 
{ 
    public PropertyPath Path { get; set; } 

    public override object ProvideValue(IServiceProvider serviceProvider) 
    { 
     var binding = new Binding() 
     { 
      Path = Path, 
      Converter = new TimeOfDayConverter(), 
     }; 
     binding.ValidationRules.Add(new ValidateTimeOfDay() 
     { 
      ValidatesOnTargetUpdated = true, 
     }); 
     return binding.ProvideValue(serviceProvider); 
    } 
} 

鑑於你控制的名字,你可能還需要使用一個時間選擇器控件,而不是的文本框。看看這個問題:What is currently the best, free time picker for WPF?

+0

感謝Quartermeister。時間選擇器正是我所需要的。另外,感謝您使用標記擴展選項。這是我今天學到的其他東西。乾杯。 – 2010-08-09 00:39:42

1

樣式只能包含一組可用於多個控件的屬性。在你的情況下,轉換器和驗證規則不適用於文本框,而是應用於綁定的內容,因此它們僅適用於單個元素,不能用於樣式。

+0

啊!當然!感謝您指出了毛裏齊奧:) – 2010-08-09 00:43:57