我想将List中的String元素绑定到Textbox。当我点击一个元素时,文本会被更新。但是当列表中的元素更改时,文本框文本不会更改。。
我的代码如下:
XAML:
<TextBlock Foreground="White" Name="xTitel" Text="{Binding Titel}" Width="200" FontSize="36" FontWeight="Bold"/>
点击功能:
foreach (Channel c in App.Connector.ChannelList)
{
if (c.StationName == StationName)
{
Binding b = new Binding();
b.Source = c.CurrentTitle;
xTitel.SetBinding(TextBlock.TextProperty, b);
}
}
通道定义:
public class GlobalVariables : INotifyPropertyChanged
{
public static MediaElement mediaElement;
private ObservableCollection<Channel> channelList;
public ObservableCollection<Channel> ChannelList
{
get { return channelList; }
set
{
channelList = value;
NotifyPropertyChanged("ChannelList");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
编辑:
我忘了说什么:
在我的XAML中,我有一个GridView,它与Channellist绑定一起工作。如果我是正确的,每次当我的Gridview更新时,文本框都应该更新。这是我的Gridview:
<local:VariableGridView
IsSwipeEnabled="True"
Background="Transparent"
x:Name="itemGridView"
Margin="0,0,0,-3"
Padding="116,0,40,46"
SelectionMode="None"
IsItemClickEnabled="True"
ItemClick="ItemView_ItemClick"
Grid.RowSpan="2"
>
<local:VariableGridView.ItemsPanel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid Background="Transparent" Orientation="Vertical" ItemWidth="120" ItemHeight="120"/>
</ItemsPanelTemplate>
</local:VariableGridView.ItemsPanel>
<local:VariableGridView.ItemTemplate>
<DataTemplate>
<Grid Background="{Binding Background}">
<StackPanel Orientation="Horizontal" Margin="10,0,0,0">
<Image x:Name="CurrentCover" Source="{Binding CurrentCover}" Width="90" Height="90"/>
<StackPanel Orientation="Vertical" HorizontalAlignment="Left" Margin="10,25,10,10">
<TextBlock Foreground="White" Text="{Binding Name}" Width="200" FontSize="24" FontWeight="Bold"/>
<TextBlock Foreground="White" Text="{Binding CurrentArtist}" Width="200" FontSize="12" FontWeight="Bold" />
<TextBlock Foreground="White" Text="{Binding CurrentTitle}" Width="200" FontSize="12" />
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</local:VariableGridView.ItemTemplate>
</local:VariableGridView>
信道类别:
public class Channel : INotifyPropertyChanged
{
public int Width { get; set; }
public int Height { get; set; }
public string Logo { get; set; }
public string StationName { get; set; }
public string Color { get; set; }
public SolidColorBrush Background { get; set; }
//public string Name { get; set; }
private string name;
public string Name
{
get { return name; }
set
{
name = value;
NotifyPropertyChanged("Name");
}
}
//..... More Code ...
}
(这个Gridview中的文本框会更新。但我想在代码上设置绑定的其他文本框不会更新)
应该是这个吗?
Binding b = new Binding("CurrentTitle");
b.Source = c;
xTitel.SetBinding(TextBlock.TextProperty, b);
编辑以解释更多内容:如果直接绑定到字符串属性,则不会看到更改,因为字符串是不可变的。它将永远固定在原始字符串上。您必须绑定到持有字符串属性的对象,并为绑定提供一个属性名称(路径)以监视对的更改。