簡體   English   中英

使用 MVVM 在 wpf 中處理標簽的內容更改事件

[英]Handling Label's Content changed event in wpf using MVVM

此標簽存在於用戶控件中,我將此標簽的 Content 屬性綁定到 Window 的數據上下文。 每當此標簽的內容更改時,我都想執行 ICommand。 它綁定到的屬性在父視圖模型中。 雖然我在用戶控件的視圖模型中有一個 ICommand。

    <Label Style="{StaticResource LabelStyle}" 
         FontSize="28" HorizontalAlignment="Center" 
         Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}, 
         Mode=FindAncestor}, Path=DataContext.CurrentTag}">
    </Label>

我發現了一種更適合MVVM模式的方法。

交互性來自命名空間下方

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

設置NotifyOnTargetUpdated=True ,可使TargetUpdated事件觸發我綁定ICommand的位置

 <Label Style="{StaticResource LabelStyle}" FontSize="28" HorizontalAlignment="Center" 
             Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}
                        ,Mode=FindAncestor}
            , Path=DataContext.CurrentTag, NotifyOnTargetUpdated=True}" >
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="TargetUpdated">
                    <i:InvokeCommandAction Command="{Binding SubmitCommand}" 
                                           CommandParameter="{Binding 
                               RelativeSource={RelativeSource AncestorType={x:Type Window}
                                ,Mode=FindAncestor}, Path=DataContext.CurrentTag}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Label>

Label沒有要處理的ContentChanged事件。

您可以做的是使用DependencyPropertyDescriptor並使用其AddValueChanged方法以編程方式連接事件處理程序:

public partial class MyUserControl : UserControl
{
    public MyUserControl ()
    {
        InitializeComponent();
    DataContext = new YourViewModelClass();

        DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(Label.ContentProperty, typeof(Label));
        if (dpd != null)
        {
            dpd.AddValueChanged(label, OnLabelContentChanged);
        }
    }

    private void OnLabelContentChanged(object sender, EventArgs e)
    {
        var vm = this.DataContext as YourViewModelClass;
        vm.YourCommand.Execute(null);
    }
}

在視圖中處理對依賴項屬性的更改: https : //blog.magnusmontin.net/2014/03/31/handling-changes-to-dependency-properties/

<Label x:Name="label"
         FontSize="28" HorizontalAlignment="Center" 
         Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}, 
         Mode=FindAncestor}, Path=DataContext.CurrentTag}">
</Label>

如前所述, Label沒有ContentChanged事件。

但是,當我需要此屬性工作時,我改用SizeChanged事件。

我所做的就是每當更改Label的內容時,都使用接近原始寬度的值來更改其寬度。

由於Label不顯示邊緣,因此,除非您附近沒有其他任何工具, Label長度沒有關系。

我知道這不是解決此問題的確切且正式的解決方案,但它挽救了我的生命。

Label沒有ContentChanged事件,但TextBox確實有TextChanged事件。

如果您禁用IsHitTestVisible並將BorderBrushBackground變為不可見,那么它看起來與 Label 幾乎相同並且不可寫,因此它的功能也相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM