0

I had try the following, but got syntax error.

class A {
    public static int[] Numbers { get; } = new[] { 1, 2, 3 };
}
<TextBlock Text="{x:Static A.Numbers[0]}" />  <!-- syntax error --> 
huang
  • 919
  • 11
  • 22

1 Answers1

1

"x:Static" only supports accessing members of the type. See the documentation: StaticExtension Class.

To use a path (and the index is part of the path) you need a binding. An example of such a binding:

<TextBlock Text="{Binding [0], Source={x:Static lib:A.Numbers}}" />

Where lib: is the prefix associated with the namespace in which class A resides.

Or use a more modern binding syntax (since WPF 4.5):

<TextBlock Text="{Binding (lib:A.Numbers)[0]}" />

P.S. Also, to eliminate possible errors, you should change the implementation of the Numbers property - protect the collection from change or make it observable.
Example:

    public class A
    {
        public static ReadOnlyCollection<int> Numbers { get; } = Array.AsReadOnly(new int[] { 1, 2, 3 });
        // Or
        public static ObservableCollection<int> Numbers { get; } = new ObservableCollection<int> () { 1, 2, 3 };
    }
Clemens
  • 123,504
  • 12
  • 155
  • 268
EldHasp
  • 6,079
  • 2
  • 9
  • 24
  • @Clements , `"{Binding (lib:A.Numbers)[0]}"` works for me in runtime, but doesn't work in Design Mode. Returns an empty value. Does this expression in Design Mode work correctly for you? – EldHasp Nov 19 '22 at 20:33