我在我的視圖中有一個TextBlock
控件,其Width
取決於Text
屬性。在MVVM中綁定到TextBlock Width屬性
我正在尋找一些方法來綁定的TextBlocks Width
的財產在我的模型,將工作方式如下:
- 的
Width
的設置必須根據自動完成對Text
- 在我按一下按鈕,我想找回寬度
我嘗試下面的代碼,但它使Width
爲0,如果我不明確設置它的構造函數查看model.Tried Mode=OneWayToSource
和Mode=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());
}
}
這只是爲了佈局的目的?還是有什麼理由你真的需要明確設置寬度?如果要進行佈局,最好在「自動」寬度規格上進行中繼。 – Nathan
我不需要根據文本設置它必須自動調整的寬度,我只是希望能夠從視圖模型中訪問寬度 –