Reputation: 117
I would like to create a WPF class library based on a TreeView
to visualize JSON strings.
I define a JsonProperty
DependencyProperty
which I wan't to use to pass the JSON string. I'm able to get the string in the JsonChangedCallback
without DataContext
. When I add a DataContext
to the ViewModel
, the JsonChangedCallback
is not longer reached. I'm not so sure how I will achieve it yet, but I believe that a specific ViewModel
will be required to handle the TreeView
node expansions.
For the time being, I don't want to load the JSON string from a file, but directly provide it from the consumer app. I'll probably change it later on if performances matter.
I believe that if I don't specified a ViewModel
in the View
of the class library it takes the one from the consumer app. I don't get any binding error though.
How can I specified a specific ViewModel
, but still reach the JsonChangedCallback
?
<UserControl xmlns:visualizer="clr-namespace:Visualizer;assembly=Visualizer.Desktop">
<visualizer:JsonVisualizer Json="{Binding Json, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</UserControl>
<TreeView x:Class="Visualizer.JsonVisualizer">
<TreeView.Resources>
<!-- Not sure if something like that can help.. -->
<Style TargetType="{x:Type local:JsonVisualizer}">
<Setter Property="Json" Value="{Binding JsonProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource Self}}" />
</Style>
</TreeView.Resources>
</TreeView>
public partial class JsonVisualizer : TreeView
{
#region Public Static Readonly Members
public static readonly DependencyProperty JsonProperty =
DependencyProperty.Register(
nameof(Json),
typeof(string),
typeof(JsonVisualizer),
new PropertyMetadata(null, JsonChangedCallback));
public string Json
{
get => (string)GetValue(JsonProperty);
set => SetValue(JsonProperty, value);
}
public JsonVisualizer()
{
InitializeComponent();
//DataContext = new JsonVisualizerViewModel();
}
private static void JsonChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var json = e.NewValue;
// Code reached if no DataContext specified in the constructor.
}
}
Upvotes: 0
Views: 89