2013-02-01 131 views
0

我在我的視圖中有一個TextBlock控件,其Width取決於Text屬性。在MVVM中綁定到TextBlock Width屬性

我正在尋找一些方法來綁定的TextBlocks Width的財產在我的模型,將工作方式如下:

  1. Width的設置必須根據自動完成對Text
  2. 在我按一下按鈕,我想找回寬度

我嘗試下面的代碼,但它使Width爲0,如果我不明確設置它的構造函數查看model.Tried Mode=OneWayToSourceMode=OneWay但它沒有區別,有什麼建議嗎?

查看:

<Grid> 
    <TextBlock Text="Some text" Width="{Binding TextWidth,Mode=OneWayToSource}" /> 
    <Button Content="Show Width" Height="30" Width="90" Command="{Binding ShowTextWidth}" /> 
</Grid> 

視圖模型:

public event PropertyChangedEventHandler PropertyChanged; 

public void OnPropertyChanged(string propertyName) 
{ 
    if (PropertyChanged != null) 
     PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
} 

private DelegateCommand<object> showTextWidth; 
public DelegateCommand<object> ShowTextWidth 
{ 
    get { return showTextWidth; } 
    set { showTextWidth = value; } 
} 

private double textWidth; 
public double TextWidth 
{ 
    get { return textWidth; } 
    set 
    { 
     textWidth = value; 
     OnPropertyChanged("TextWidth"); 
    } 
} 

public ViewModel() 
{ 
    //If I explicitly specify the width it works: 
    //TextWidth = 100; 
    ShowTextWidth = new DelegateCommand<object>(ShowWidth); 
} 

private void ShowWidth(object parameter) 
{ 
    MessageBox.Show(TextWidth.ToString()); 
} 

}

+0

這只是爲了佈局的目的?還是有什麼理由你真的需要明確設置寬度?如果要進行佈局,最好在「自動」寬度規格上進行中繼。 – Nathan

+0

我不需要根據文本設置它必須自動調整的寬度,我只是希望能夠從視圖模型中訪問寬度 –

回答

1

寬度上的TextBlock一個DependencyProperty。在這種情況下,它是綁定的目標,TextWidth是綁定的源代碼。 OneWayToSource似乎是要走的路,你將TextWidth設置爲100,在ViewModel中沒有傳播到TextBlock的寬度,因爲它的OneWayToSource是正確的,寬度(目標)然後將TextWidth(Source)設置爲Double.NaN,因爲OneWayToSource和這就是爲什麼你看到0 ...

ActualWidth應該像sa_ddam213說的工作,但也認爲當文本更改,因爲它跨越您的網格佈局的總寬度,您的TextBlock不增長寬度(ActualWidth) 。將其置於寬度設置爲自動的ColumnDefinition中,或者將Horizo​​ntalAlignment設置爲Left,以在Text更改時查看ActualWidth更改。

我對源代碼進行了一些更改。考慮在按鈕上使用CommandParameter?退房的鏈接...

WpfApplication10.zip

0

你不是真的需要設置寬度,如果你選擇佈局面板至極可以處理這個給你。

例如。與寬度的columndefinition =自動帶你的文字

+0

我需要寬度來進行大小計算,我的問題中的示例僅適用於簡單 –

+1

你寫的寬度必須基於文本自動調整大小。 wpf layoutcontainer可以處理這個。所以我不知道你爲什麼要計算一些。順便說一句,你應該檢索ActualWidth,如果你想知道acutal寬度。 – blindmeis

0

增長要設置寬度取決於其含文字,你可以寬度屬性綁定到文本屬性,並使用一個轉換器,像這樣:

<TextBlock Width="{Binding RelativeSource={RelativeSource Self}, Path=Text, Converter={StaticResource TextToWidth}}" 

你轉換器可能看起來像:

TextBlock tb = new TextBlock(); 
tb.Text = value.ToString(); 
tb.Measure(new Size(int.MaxValue, 20)); //20 if there shouldnt be a linebreak 
return tb.DesiredSize.Width; 
+0

寬度應該基於文本自動設置,我只需要一些方法來訪問TextBlock寬度使用我的視圖模型中的屬性,因爲我需要做一些額外的計算基於這個尺寸 –

+0

在我的例子中,寬度是根據文本。如果你需要做額外的計算,爲什麼不在轉換器中做這些? –

+0

我需要在視圖模型中進行這些計算,這就是爲什麼它應該理想的屬性 –