Context: I am prototyping in prep for (maybe) converting my WinForms app to WPF.
I make very simple tree view event handler for which the code is:
var treeViewItem = (TreeViewItem)e.NewValue;
var treeViewItemTag = treeViewItem.Tag;
if (treeViewItemTag == "ViewForAMs")
{
ObjectQuery<AccountManagerView> oq = entities.AccountManagerViews;
var q =
from c in oq
select c;
dataGrid1.ItemsSource = q.ToList();
}
and the XAML is:
<Window x:Class="AccountingWpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<DockPanel>
<TreeView Name="treeView1" ItemsSource="{Binding Folders}"
SelectedItemChanged="treeView1_SelectedItemChanged">
<TreeViewItem Header="Account Manager View" Tag="ViewForAMs"/>
</TreeView>
<DataGrid AutoGenerateColumns="True" Name="dataGrid1" />
</DockPanel>
</Window>
When I ran it, I fully expected to see my data grid get populated but the == comparison failed on the second line of code above.
The debugger shows this:
QUESTION: why were there no compile or runtime errors? (same question another way: what is actually being compared such that the == operator outputs FALSE?)
Cast the Tag
to string
first. In the default implementation on object
, ==
compares references. As the Tag
property is of type object
, it is using the lowest common ==
operator between object
and string
, which is the object
implementation. By casting Tag
to string
, the implementation on string
is used, which is a value comparision.
Use Object.Equals(treeViewItemTag, "ViewForAMs")
instead
If you look at the type of treeViewItemTag, you will see that the type is object, not string. So when you use ==, you are comparing the references of two objects. That will always return false in this case. If you use Equals() instead, or cast to a string, then it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With