我有一个 TextBlock
在我看来控制,它的Width
取决于 Text
属性(property)。
我正在寻找某种方法来绑定(bind) TextBlocks Width
到我的模型中的一个属性,它将按如下方式工作:
Width
的设置必须根据 Text
自动完成我试过下面的代码,但它保留了
Width
如果我没有在 View 模型的构造函数中显式设置它,则为 0。试过 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());
}
}
最佳答案
最终创建了附加行为 by Maleak受 Kent Boogaarts Pushing read-only GUI properties back into ViewModel 的启发,不敢相信将ActualWidth的值插入 View 模型有这么复杂!
关于c# - 绑定(bind)到 MVVM 中的 TextBlock Width 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14640932/