0

How can I bind the Content of a Label to ViewModel.Config.UnitList[1].Dim?

Config is a static property of the DataContext ViewModel, ListUnit is a List and Dim is a string.

I tried all kinds of things, like:

LBUnit="{Binding Source=DataContext.Config, Path=UnitList[1].Dim}"

LBUnit="{Binding Source=ViewModel.Config, Path=UnitList[1].Dim}"

LBUnit="{Binding Path=ViewModel.Confg.UnitList[1].Dim}"

And using this one from AIC (the last block)

[ContentProperty("Parameters")]
public class PathConstructor : MarkupExtension
{
public string Path { get; set; }
public IList Parameters { get; set; }

public PathConstructor()
{
    Parameters = new List<object>();
}

public PathConstructor(string b, object p0)
{
    Path = b;
    Parameters = new[] { p0 };
}

public override object ProvideValue(IServiceProvider serviceProvider)
{
    return new PropertyPath($"(ViewModel.Config.UnitList[{Index}].Dim)")
}
}

(property path adapted)

dymanoid
  • 14,771
  • 4
  • 36
  • 64
Erik
  • 894
  • 1
  • 8
  • 25
  • 1
    Possible duplicate of [How can I bind a xaml property to a static variable in another class?](https://stackoverflow.com/questions/15854708/how-can-i-bind-a-xaml-property-to-a-static-variable-in-another-class) – Sinatr Jan 11 '19 at 15:43

1 Answers1

2

You can achieve that by using the x:Static Markup Extension

Note: Use this only if ViewModel.Config doesn't change!

LBUnit="{Binding Source={x:Static local:ViewModel.Config}, Path=UnitList[1].Dim}"

When ViewModel.Config may change, you can bind like so

LBUnit="{Binding Path=(local:ViewModel.Config).UnitList[1].Dim}"

This has benefit that you can use static property change notification like descriped here

nosale
  • 808
  • 6
  • 14
  • Indeed. Thnx. Thus "factoring out" the static property Config into the Source. Knowing that the entire Config is static and its content always remains the same after reading it from an XML file,(readonly?) , is there something to be gained from that knowledge? BTW. I found that {Binding Config.UnitList[1].Dim} also works. – Erik Jan 11 '19 at 18:58
  • You may use [`BindingMode.OneTime`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.data.bindingmode?view=netframework-4.7.2) – nosale Jan 11 '19 at 20:08
  • Did not know that `{Binding Config.UnitList[1].Dim}` works but I still would not use it because when you read that you would expect that `Config` is an instance member (just my opinion). – nosale Jan 11 '19 at 20:40