c# - 绑定(bind)到 MVVM 中的 TextBlock Width 属性

标签 c# wpf mvvm

我有一个 TextBlock在我看来控制,它的Width取决于 Text属性(property)。

我正在寻找某种方法来绑定(bind) TextBlocks Width到我的模型中的一个属性,它将按如下方式工作:

  • Width 的设置必须根据 Text 自动完成
  • 在我的按钮单击中,我想检索宽度

  • 我试过下面的代码,但它保留了 Width如果我没有在 View 模型的构造函数中显式设置它,则为 0。试过 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());
    }
    

    }

    最佳答案

    最终创建了附加行为 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/

    相关文章:

    c# - 异步文件读取比同步或手动线程慢 40 倍

    wpf - 触发 Button.Click 时的 XAML Binding.UpdateSourceTrigger?

    c# - TabControl中的WPF MVVM多个ContentControls

    C# Vlc.DotNet 库 - 空引用异常

    c# - 无法使用 C# 服务打开 xls 文件

    c# - 如何为每个 StackPanel 项目设置单独的工具提示?

    mvvm - 使用 Caliburn MVVM 彻底分离 UI

    c# - 列表中的按钮数据绑定(bind)行为不正确

    c# - 尝试在我的 WebAPI 上调用特定的 GET 方法,但未找到 HTTP 404

    c# - 使用 MVVM 在 Windows 商店应用程序中更改框架