1

i am adding "MiniTextBlock" Text to my list box through below code, and when i click on that list box item then it will show to "ShowTextBlock" and selected item is highlighted in listbox, but if "Show TextBlock" Text is changed then selected item is still highlighted so i want it should deselect automatically. For this purpose i am using this answer, but it only work when i add list box item directly through Xaml, if i am using template binding it is not working.

XAML

<ListBox x:Name="FavoritesListBox" VerticalAlignment="Center"                         
                 Background="Transparent" Height="150"
                 ScrollViewer.HorizontalScrollBarVisibility="Auto"
                 ScrollViewer.VerticalScrollBarVisibility="Disabled"                     
                 SelectionChanged="FavoritesListBox_SelectionChanged">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Visibility="Visible" x:Name="FavoritesListBoxTextBlock" 
                               FontSize="30" Text="{Binding MyLists}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
</ListBox>

<Button Name="AddToFavoriteButton" Click="AddToFavoriteButton_Click" />

<TextBLock Name="MiniTextBlock" /> <!-- This will Contain diffrent texts -->

<TextBLock Name="ShowTextBlock" /> <!-- This will show list box selected item, but text can be change from other source so listbox selected item should deselect automatically -->

C#

Constructor

IsolatedStorageFile Settings1 = IsolatedStorageFile.GetUserStoreForApplication();
MyDataList listobj = new MyDataList();

On Initializing

public MainPage()
{
    this.InitializeComponent();

    //Populating ListBox items
    if (Settings1.FileExists("MyStoreItems"))
    {
        using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Open))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList));
            listobj = (MyDataList)serializer.ReadObject(fileStream);
        }
    }
    FavoritesListBox.ItemsSource = listobj;

    //Checking whether selected item is equal to show textblock or not.
    DispatcherTimer timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(0) };
    timer.Tick += delegate (object sender, object e)
    {
        var selectedItem = FavoritesListBox.SelectedItem;

        if (selectedItem != null && selectedItem.ToString() != ShowTextBlock.Text)
        {
            FavoritesListBox.SelectedIndex = -1; //but it deselect item even if selected selected item is equal to Show Text Block.
        }
    };
    timer.Start();
}

Codes

private void AddToFavoriteButton_Click(object sender, RoutedEventArgs e)
{
    listobj.Add(new MyData { MyLists = MiniTextBlock.Text });

    //MiniTextBlock Which contains simple digit like 35 which will goto ListBox through this button

    using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MyStoreItems", FileMode.Create))
    {
        DataContractSerializer serializer = new DataContractSerializer(typeof(MyDataList));
        serializer.WriteObject(fileStream, listobj);
    }
}


public class MyData
{
    public string MyLists { get; set; }
}

public class MyDataList : ObservableCollection<MyData> //for storing mydata class items with type of list
{

}

//Selection Change for hint purpose

private void FavoriteListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    MyData selecteddata = (sender as ListBox).SelectedItem as MyData;

    if (selecteddata != null)
    {
        ShowTextBlock.Text = selecteddata.MyLists.ToString());

        using (IsolatedStorageFileStream fileStream = Settings1.OpenFile("MySelectedStoreItem", FileMode.Create))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(MyData));
            serializer.WriteObject(fileStream, selecteddata);
        }
    }
}
Arpit Jain
  • 107
  • 11
  • 1
    You comment "*but it through exception*" - please include the exception message and stack trace. You use `selectedItem.ToString()` where you should use `((MyData)selectedItem).MyLists`. – grek40 Oct 27 '17 at 09:30
  • @grek40 sorry my mistake i test it again and it deselect item even if selected selected item is equal to Show Text Block. Now i put everything this question so you can understand easily whats going on – Arpit Jain Oct 27 '17 at 12:06
  • Summary = a button which minitextblock text to list box using isolated storage with mydata class. and if i click on that item in listbox it will appear on showtextblock but there is a case which change show textblock text directly from onlne(which is not related to this question) so selected item in listbox should be deselect – Arpit Jain Oct 27 '17 at 12:13
  • Again... `if (selectedItem != null && selectedItem.ToString() != ShowTextBlock.Text)` is not good, because `ToString()` does not return `MyData.MyLists` – grek40 Oct 27 '17 at 14:16
  • @grek40 that's my question how can i implement it – Arpit Jain Oct 27 '17 at 14:27
  • Did you already read and understand my first comment? – grek40 Oct 27 '17 at 14:33
  • 1
    @grek40 oh! i forget that comment it works .. Thanks You :) thats the mistake i am done. you can update your answer so i can mark it as answer – Arpit Jain Oct 28 '17 at 06:10
  • Updated the answer. – grek40 Oct 29 '17 at 22:25

1 Answers1

1

You can use the SelectedValue property to select / unselect items based on the ShowTextBlock.Text value. However, I'm not 100% clear on your intended data flow. If you describe in more detail, which events should lead to what kind of displayed data / selection, I can update the answer with more details.

<ListBox x:Name="FavoritesListBox"
         SelectedValuePath="MyLists"
         SelectedValue="{Binding ElementName=ShowTextBlock,Path=Text,Mode=OneWay}">

If you want to compare the selected item to the textblock contents, cast the selected item to your datatype and compare its text property MyLists

if (selectedItem != null && ((MyData)selectedItem).MyLists != ShowTextBlock.Text)
{
    // ...
}
grek40
  • 13,113
  • 1
  • 24
  • 50
  • selected item is not deselecting if show text block text is changed and i followed this http://bsubramanyamraju.blogspot.in/2014/01/how-to-store-listbox-items-into.html example for storing items in list box – Arpit Jain Oct 27 '17 at 08:00
  • i am using time ticker for checking selected item is equal to show textblock or not as you can see in this question https://stackoverflow.com/questions/46745544/selected-item-always-deselect-c , it works fine if directly add list box item directly but through exception if i use template binding in current question – Arpit Jain Oct 27 '17 at 08:06
  • Well I don't know what you do in detail, but I changed `ShowTextBlock` to be a `TextBox` for testing and when I write some text into it, the listbox items are selected / deselected according to my input. By the way: if you want to change `ShowTextBlock.Text` when you select an item, you should change the `Binding.Mode` - but that's why I say you should describe the data flow in detail (edit your question instead of writing comments) – grek40 Oct 27 '17 at 08:08
  • are you checked my previous question https://stackoverflow.com/questions/46745544/selected-item-always-deselect-c/46752442#46752442 ? – Arpit Jain Oct 27 '17 at 08:10
  • @ArpitJain yes, but it (1) your question should be self-contained, so please provide all necessary information in your current question (2) it is different, since you don't work with `ItemsSource` over there and (3) it is irrelevant because if you focus on the desired result, a better code/xaml structure is possible. – grek40 Oct 27 '17 at 08:16
  • can you also help me in this question https://stackoverflow.com/questions/46544844/storyboard-animation-is-lagging because this question is view by very less people so i am not getting any answer bu a hint in comment to convert code to xaml – Arpit Jain Oct 31 '17 at 12:28