2009-07-20 172 views
2

我創建了一個用戶控件和一個關聯的視圖模型。視圖模型的屬性「DisplayName」和「TimeIntervalLength」顯示在用戶控件視圖DataBinding中。根據視圖模型的屬性,我想更新控件的寬度。 寬度應該是「TimeIntervalLength」,但至少是「DisplayName」。我試圖重寫「OnPropertyChanged」,但這不起作用。此外,我找不到一個適當的事件來覆蓋。使用DataBinding值更新控件的寬度(WPF)

在此先感謝。

+0

這將在確定根本原因幫助,如果你是如何您的綁定聲明,你可以張貼。它可能是各種不同的問題。謝謝! – 2009-07-20 15:03:20

回答

1

你可以嘗試在你的UserControl上沒有指定寬度/高度。它應該適合於內部託管的控件。

<UserControl x:Class="MyUserControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <StackPanel> 
     <TextBlock x:Name="TextBlock1" Text="DisplayName Goes Here" /> 
     <local:TimeIntervalControl x:Name="TimeInterval" /> 
    </StackPanel> 
</UserControl> 

另一種選擇是使用IValueConverter做一些更重的起重:

<UserControl x:Class="MyUserControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <UserControl.Resources> 
     <local:MaxValueConverter x:Key="MaxValue" /> 
    </UserControl.Resources> 
    <UserControl.Width> 
     <MultiBinding Converter="{StaticResource MaxValue}"> 
      <Binding Path="ActualWidth" ElementName="TextBlock1" /> 
      <Binding Path="ActualWidth" ElementName="TimeInterval" /> 
     </MultiBinding> 
    </UserControl.Width> 
    <StackPanel> 
     <TextBlock x:Name="TextBlock1" Text="DisplayName Goes Here" /> 
     <local:TimeIntervalControl x:Name="TimeInterval" /> 
    </StackPanel> 
</UserControl> 

重型起重在MaxValueConverter:

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
{ 
    if (values == null) 
    { 
     return Binding.DoNothing; 
    } 

    return values.Max(obj => (obj is double) ? (double)obj : 0.0); 
} 
+0

元評論:ActualWidth並不總是顯示已經改變,尤其是如果你應用了一個LayoutTransform。您可能需要添加其他邏輯才能重新評估綁定。 – user7116 2009-07-20 15:52:27

0

不能完全確定,如果我理解正確的,但它聽起來像最簡單的事情將是一個計算的屬性從視圖添加到您的視圖模型,然後綁定到:

// In your model 
public int DisplayWidth { 
    get { return CalculateDisplayWidth(); } // todo 
} 

(很明顯,你可以用你需要的任何東西代替「CalculateDisplayWidth()」)

<!-- In your view --> 
<UserControl x:Class="MyUserControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="{Binding Path=DisplayWidth, Mode=OneWay}"> 

</UserControl> 
0

而不是控制寬度,控制MinWidth。並清除Width屬性在用戶控件的構造函數:

this.ClearValue(WidthProperty);