2014-03-12 106 views
1

我有一個TextBox,它向用戶顯示一個文件路徑。用戶可以使用OpenFileDialog來選擇文件,這會更新文本,或者直接將文件寫入/粘貼到文本框中。ValueConversion only only when not selected

但是,文本框的大小受到限制,爲了避免路徑被切斷,我使用自定義IValueConverter來切斷部分路徑以確保驅動器號和文件名都可見。

例如, C:\Users\USERNAME\Documents\CompanyName\ExportType\ExportName\Exportfile1.bin
變得
C:\...\ExportType\ExportName\Exportfile1.bin

然後,當用戶選擇的字段,會出現問題。正如預期的那樣,IValueConverter的ConvertBack方法被觸發,現在的值是縮短的路徑。

是否可以在不創建一些自定義複雜的自定義控件的情況下在未選中時顯示一個格式化值,並在選擇時顯示原始值?

(我有機會獲得Telerik的UI組件,如果它已經存在這樣的組件)

+0

也許觸發引發事件PreviousMouseDown更改屬性使用併發提及的轉換器和觸發事件PreviousMouseUp爲了恢復到以前的值的文本。請記住,對於文本框事件MouseDown/Up不會引發。 – Maximus

+0

PreviewMouseDown(我猜你在那裏有一個錯字?)不是一個解決方案。用戶可以選中它。 – AkselK

+0

將Focusable設置爲false以停用。但是我越來越困惑你想達到什麼。 – Maximus

回答

1

我想出瞭解決方案,而後面的代碼

 <TextBox> 
     <TextBox.Style> 
      <Style TargetType="TextBox"> 
       <Setter Property="Text"> 
        <Setter.Value> 
         <Binding Path="nazwa" Converter="{StaticResource converter}" ConverterParameter="false"/> 
        </Setter.Value> 
       </Setter> 
       <Setter Property="Foreground" Value="Red"/> 
       <Style.Triggers> 
        <Trigger Property="IsFocused" Value="True"> 
         <Setter Property="Foreground" Value="Gold"/> 
         <Setter Property="Text"> 
          <Setter.Value> 
           <Binding Path="nazwa" Converter="{StaticResource converter}" ConverterParameter="true"/> 
          </Setter.Value> 
         </Setter> 
        </Trigger> 
       </Style.Triggers> 
      </Style> 
     </TextBox.Style> 
    </TextBox> 

轉換

public class conv : IValueConverter 
{ 
    private string track = null; 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
      track = value.ToString(); 
     return parameter.ToString().Equals("true") ? track: track.Substring(0,2); 
    } 

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

結果當文本框未被選中時 enter image description here

當我選擇 enter image description here 只是改變顏色,還有。訣竅是改變發送到轉換器的參數。讓我知道它是否有效。

+0

啊,所以你不要使用靜態綁定,聰明。我通過在IsFocused觸發器中不包含轉換器來改進了這一點。很棒! – AkselK