Frage

Please consider the following XAML markup (App.xaml file in Visual Studio 2010):

<Application x:Class="UpdateTrigger.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:UpdateTrigger"
             xmlns:clr="clr-namespace:System;assembly=mscorlib"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <clr:String x:Key="MyString">My string</clr:String>
    </Application.Resources>
</Application>

Can I write into MyString much like a variable in a C# program? That is what I am trying to do: I am trying to declare and define a variable through pure XAML, without any code-behind. Is this possible?

CLARIFICATION EDIT:

If I bind MyString, for example, to a TextBox in XAML, can a user type into that TextBox? I tried, but have not been able to do this.

War es hilfreich?

Lösung

Is it possible to bind to and modify a resource object? Yes and no. You can do it but the object needs to be mutable, so can't be a value type like an Int32 or Boolean, or String which is an immutable reference type. The object also needs to have some property that is being modified (the Path of the Binding) - you can't replace the entire object itself.

The more important question is probably, should you do this. The answer to that is usually no but there can be cases where it can sometimes be useful, for example, declaring a ViewModel instance directly in the View XAML to provide easy designer support. In general it's almost always better to be binding to objects that are part of your code so they can easily interact with other parts of your program without relying on runtime resource lookups. If you have data that's staying in the view, like a TextBlock that just mirrors the value of a TextBox, it's usually better just to bind them directly together with an ElementName Binding rather than adding an extra middleman.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top