0

嘿,我不确定为什么我会遇到这样的困难,但我需要能够根据我的程序是否检测到互联网连接来更改瓷砖isEnabled属性。

我正在使用并需要更改的 WPF 代码如下:

<dxlc:TileLayoutControl x:Name="tileLayoutControl1" Margin="150,63,153,57" Padding="5"
   AllowAddFlowBreaksDuringItemMoving="False" AllowItemMoving="False" Orientation="Horizontal" ScrollBars="None"
   TileClick="tileLayoutControl1_TileClick">
</dxlc:TileLayoutControl>

这在启动时由后面的代码填充:

private void createMenu()
{
   List<String> menuIcons = new List<string>();
        
   menuIcons.Add("gamesIcon.png");
   menuIcons.Add("movieIcon.png");
   menuIcons.Add("musicIcon.png");
   menuIcons.Add("televisionIcon.png");
   menuIcons.Add("youTubeIcon.png");
   menuIcons.Add("androidIcon.png");

   foreach (String item in menuIcons)
   {
       Image finalImage = new Image();
       BitmapImage image = new BitmapImage();

       image.BeginInit();
       image.UriSource = new Uri("/img/" + item.ToString(), UriKind.Relative);
       image.EndInit();

       finalImage.Source = image;
       image = null;

       tileLayoutControl1.Children.Add(new Tile()
       {
           Content = finalImage,
           Name = item.ToString().Replace(".png", ""),
           Tag = item.ToString().Replace(".png", "").Replace(".jpg", ""),
           Width = 255,
           Height = 288,
           IsEnabled = false,
           Margin = new Thickness(0, 0, 50, 20),
           Background = Brushes.Transparent,
           BorderThickness = new Thickness(0, 0, 0, 0)
       }
    }
}

最后是我在计时器内检查互联网连接的代码:

private bool checkInternet()
{
    try
    {
        Ping myPing = new Ping();
        PingReply reply = myPing.Send("google.com", 1000, new byte[32], new PingOptions());

        return (reply.Status == IPStatus.Success);
    }
    catch (Exception)
    {
        return false;
    }
}

public firstWindow()
{
    InitializeComponent();
    var startTimeSpan = TimeSpan.Zero;
    var periodTimeSpan = TimeSpan.FromMinutes(5);

    var timer = new System.Threading.Timer((e) =>
    {
        bool hasInternet = checkInternet();

        TileLayoutControl test = (TileLayoutControl)this.tileLayoutControl1.FindName("youTubeIcon");

        test.IsEnabled = true;
        tileLayoutControl1.RegisterName("youTubeIcon", this.isEnabled = true);
    }, null, startTimeSpan, periodTimeSpan);
}

我目前没有收到以下行的任何错误:

TileLayoutControl test = (TileLayoutControl)this.tileLayoutControl1.FindName("youTubeIcon");
test.IsEnabled = true;
tileLayoutControl1.RegisterName("youTubeIcon", this.isEnabled = true);

但是test,当我尝试单击磁贴时, RegisterName似乎没有更改isEnabled属性。

我也读过使用Command="{Binding ClickCommand}"可能是我的答案,但这似乎只与我没有用于这个粒子程序的 MVVM 类型的模式有关。

我也知道检查tileLayoutCibtril1有一个Children属性,它包含我动态创建的图标,但tileLayoutCibtril1.Children没有.FindName属性。

在此处输入图像描述

那么我错过了什么?

4

1 回答 1

0

尝试ApplyTemplateTileLayoutControlforeach 语句之后调用。的模板TileLayoutControl尚未应用,因此FindName返回nullApplyTemplate构建当前模板的可视化树

foreach (String item in menuIcons)
{
    ...
}
tileLayoutControl1.ApplyTemplate();
于 2021-09-21T10:01:42.383 回答