2009-05-10 23 views
2

バインディングを設定したいと思います。問題は、ターゲットがstring型であるが、ソースがdouble型であることです。 次のコードでは、VersionNumberはdouble型です。これを実行すると、例外をスローせずにテキストブロックが空になります。 このバインディングはどのように設定できますか?WPFで文字列を二重にバインドする方法はありますか?

<Style TargetType="{x:Type MyControl}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type MyControl}"> 
       <TextBlock Text="{TemplateBinding Property=VersionNumber}" /> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter>   
</Style> 
+0

あなたがバインドしている 'VersionNumber'プロパティがダブルではない可能性があります。なぜあなたはあなたが期待しているバインディング動作を見ていないのか説明できますか? – yzorg

答えて

5

あなたは、コンバータを必要とする:

namespace Jahedsoft 
{ 
    [ValueConversion(typeof(object), typeof(string))] 
    public class StringConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      return value == null ? null : value.ToString(); 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      throw new NotImplementedException(); 
     } 
    } 
} 

今、あなたはこのようにそれを使用することができます:

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

    <j:StringConverter x:Key="StringConverter" /> 
</ResourceDictionary> 

... 

<Style TargetType="{x:Type MyControl}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type MyControl}"> 
       <TextBlock Text="{TemplateBinding Property=VersionNumber, Converter={StaticResource StringConverter}}" /> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter>   
</Style> 
+0

.ToString形式を受け入れようとしている場合、またはSP1をお持ちでバインディングのStringFormatプロパティを使用できる場合は、このためのコンバータは必要ありません。問題は他のところです。 –

+0

これは、SP1なしでcourceが動作する一般的な方法です。 – CSharper

3

あなたはValueConverterは必要ありません。 Double to Stringターゲットはうまく動作します。原則として、Bindingは最後の手段としてToString()を呼び出します。

<Window x:Class="WpfApplication1.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     x:Name="w1"> 
     <TextBlock Text="{Binding Path=Version, ElementName=w1}" /> 
</Window> 
using System; 
using System.Windows; 
namespace WpfApplication1 
{ 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 
     } 
     public double Version { get { return 2.221; } } 
    } 
} 

問題は、あなたのバインディングソースは、あなたがそれだと思うものではないということはおそらくです:

は、ここでの例です。 通常、WPFのバインディングエラーは例外を発生させません。彼らはしかし、彼らの失敗をログに記録します。 How can I debug WPF bindings?

+0

Double to Stringターゲットは動作しません。 –

+2

Moheb、簡単な例を試してみてください。文字列への二重は非常に一般的であり、常に行われます –

4

例には若干の違いがあります。

TextまたはTextBoxプロパティをDoubleにバインドすると、デフォルトでToString()メソッドに戻ってしまうので、Texblockを直接使用するとうまく動作しますが、これを使用しようとすると機能しませんControlTemplate

次に、投稿に示唆されたような変換が必要です。

関連する問題